Sunday, February 17, 2019

Adding Middleware to Asp.Net Core

In the previous posts we saw a simple HelloWorld application which displays a message in the browser when the application runs. In this post we will further enhance the application by adding another Middleware to the execution sequence.

Any middleware addition should be done in the Configure() method of the Startup.cs file. By default the app.Run middleware will be added in a Asp.Net Core application. Any middleware addition should be done before the app.Run() middleware, since this is the last middleware processed by the runtime. Any middleware added after the app.Run() will not get executed. Now let us add one of the built in middleware UseWelcomePage to the application as follows.

Open the Startup.cs file and add the UseWelcomePage middleware before app.Run() as follows.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseWelcomePage();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

Build and run the application, you will notice that a Welcome page gets displayed in the browser instead of the Hello World message, this was done by the UseWelcomePage Middleware.



This UseWelcomePage middleware is not of much use, but helps us illustrate how to add middleware’s to the request execution pipeline.

Asp.Net Core provides many useful middleware’s for logging, exception handling, Routing, MVC etc which can be added based on the requirement. 


Search Flipkart Products:
Flipkart.com

1 comment:

Game World said...

I have been looking for this every where.

Thank God that I found your blog.