Blog

Filter posts by Category Or Tag of the Blog section!

Using and creating Middleware in asp.net core

Monday, 17 September 2018

In asp.net core application, Http requests are handled and processed by Middleware and every Http response would be created when the request has been passed to the middleware suite. For example, MvcMiddleware is one of the most used and important Middleware in asp.net core.  For using Middleware, IApplicationBuilder provides some methods with the name Use, Map and Run in starting. Look at the usage in Startup class created by asp.net core template:

 

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)

        {

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }

            else

            {

                app.UseExceptionHandler("/Home/Error");

                app.UseHsts();

            }

 

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseCookiePolicy();

           

 

            app.UseMvc(routes =>

            {

                routes.MapRoute(

                    name: "default",

                    template: "{controller=Home}/{action=Index}/{id?}");

            });

        }

 

UseStaticFiles, UseMve are the most used Middleware created by asp.net core. Now let's create a simple Custom Middleware. Look at the following class:

 

public class CustomMiddleware
{
   private readonly RequestDelegate _requestDelegate;

 

    public CustomMiddleware(RequestDelegate requestDelegate)
    {
        _requestDelegate = requestDelegate;
    }

 

    public Task Invoke(HttpContext httpContext)
    {

        return _requestDelegate(httpContext);
    }
}

 

We created a simple which is doing nothing in fact! We can use the above middleware in Startup class:

 

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)

        {

            app.UseMiddleware<CustomMiddleware>();

         }

 

Rather than HttpRequest which could be controlled by Middleware, It can also be controlled how our application looks when there is an error by Middleware:

 

 

 public class ExceptionHandlingMiddleware

    {

        private readonly RequestDelegate _requestDelegate;

 

        public ExceptionHandlingMiddleware(RequestDelegate requestDelegate)

        {

            _requestDelegate = requestDelegate;

        }

 

 

        public async Task Invoke(HttpContext context)

        {

            try

            {

                await _requestDelegate.Invoke(context);

                if (context.Response.StatusCode == StatusCodes.Status404NotFound)

                {

                    var statusCodeFeature = context.Features.Get<IStatusCodePagesFeature>();

                    if (statusCodeFeature == null || !statusCodeFeature.Enabled)

                    {

                        if (!context.Response.HasStarted)

                        {

                            await context.Response.WriteAsync("Somthing went wrong");

                            // custome error page redirection

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                throw;

            }

        }

    }

 

Middleware is playing a key point in asp.net core. You will hardly ever have to create your own middleware as plenty of middlewares have Been created by Microsoft.

Category: Software

Tags: Asp.Net

comments powered by Disqus