A middleware is a software component that is assembled into an application pipeline to handle the request and response. Asp.Net Core Middleware is replacement of Asp.net Http handler and http modules. The middleware is simple when compare to the existing handler and modules. The asp.net core request will pass to the first middleware, the middleware can response the request or calling the next piece of the middleware.
Run Method. – it will be end the execution of the middleware and return the response, it will not call the next delegate
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.Run(async context => {
await context.Response.WriteAsync("<h1>Run1</h1>");
});
app.Run(async context => {
await context.Response.WriteAsync("<h1>Run2</h1>");
});
}
Use Method- It can pass the next delegate or it can end with the current execution. In the below method await next is used to call the next pipeline to the middleware, so Use1 & Use2 will be executed.
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("<h1>Use 1</h1>");
await next();
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("<h1>Use 2</h1>");
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("<h1>Use 3</h1>");
});
Map Method _-It is used to map the separate middleware for the specific path. It allows us to define the run/use method based on our requirement.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.Map("/Login", HandleLogin);
}
private static void HandleLogin(IApplicationBuilder builder)
{
builder.Run(async context =>
{
await context.Response.WriteAsync("Login Screen");
});
}
MapWhen- it is same as map whereas we can have more condition based approach, which can be performed using querystring, header or url.
app.MapWhen(context => { return context.Request.Query.ContainsKey("auth-key"); }, HandleLogin);
Let look some of the default middleware.
UseMvc – It used to add the dependency injection of the MVC Services.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
UseMvcWithDefaultRoute – It is the default routing for the MVC
Pipeline with a default route named ‘default’ and the following template: ‘{controller=Home}/{action=Index}/{id?}’
UseStaticFiles – this will enable the static files to be served from the www root(HTML, CSS, image, and JavaScript).
UseDeveloperExceptionPage – Capture the instances from the pipelines and display the html error page.
Leave a comment