Home
Map
C#.ASP.NET
Configure Method
This page was last reviewed on Jan 4, 2024.
Dot Net Perls
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.
Note We change the lambda expression argument to UseEndpoints. In MapGet, we change the Hello World text to GetHitCount().
Note 2 GetHitCount a string that indicates the value of an int field on the Startup class. It increments the hit count.
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.
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.
UseStaticFiles
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 4, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.