ASP.NET Configure MethodCreate an ASP.NET Core Web Application and use its Configure method to run code and write output.
Configure. In an ASP.NET Core Web Application, we must set up Endpoints in the Configure method. When a visitor goes to the website, endpoints are then used.
Getting started. Please create a new ASP.NET Core Web Application in Visual Studio, and specify that it is Empty to start. We will then open the Startup class.
Configure example. In Configure, you will see some generated code such as a UseRouting and UseEndpoints call. These should be left in place.
MapGet We change the lambda expression argument to UseEndpoints. In MapGet, we change the Hello World text to GetHitCount().
GetHitCount This returns a string that indicates the value of an int field on the Startup class. It increments the hit count.
String Interpolation
Result Run the Web Application. Your browser will open, and then try refreshing the page—the hit count will increment.
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; namespace WebApplication3 { public class Startup { public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync(GetHitCount()); }); }); } int _hits; string GetHitCount() { // Increment hit count field. // ... Return string that indicates hit count. return $"Hit count: {++_hits}"; } } }
Hit count: 1
Notes, UseRouting. It is important that we leave the UseRouting call in place when we call UseEndpoints in Configure. We get an InvalidOperationException otherwise.
Error text:
System.InvalidOperationException EndpointRoutingMiddleware matches endpoints setup by EndpointMiddleware and so must be added to the request execution pipeline before EndpointMiddleware. Please add EndpointRoutingMiddleware by calling 'IApplicationBuilder.UseRouting' inside the call to 'Configure(...)' in the application startup code.
UseStaticFiles. We can call the UseStaticFiles method in Configure as well. We must add a "wwwroot" directory to store the static files for public access.
A summary. By specifying a method call in the MapGet lambda, we can execute code from the Configure method in ASP.NET Core. We can use this to begin developing a web application.
© 2007-2022 sam allen.
see site info on the changelog.