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.
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
exampleIn Configure
, you will see some generated code such as a UseRouting
and UseEndpoints
call. These should be left in place.
UseEndpoints
. In MapGet
, we change the Hello World text to GetHitCount()
.GetHitCount
a string
that indicates the value of an int
field on the Startup class
. It increments the hit count.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
UseRouting
It is important that we leave the UseRouting
call in place when we call UseEndpoints
in Configure
. We get an InvalidOperationException
otherwise.
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.
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.