| by Achyut Kendre | No comments

Built in Middleware’s in ASP.NET Core.

ASP.NET Core 3.1
Built in Middleware

Example Code: https://drive.google.com/file/d/1yxnw_0Urbg8a7EMSczlcS8-pNslkRYEM/view?usp=sharing

ASP.Net Core provides you various built in middleware, in this article we will have a look at few middleware’s.

ASP.NET Core is a modular framework. There are many middleware plug-ins available which can be used in our application.You can add the built in middle ware in request pipe line in same way, you just need to call the the method for that middle ware.
E.g. App.UseStaticFiles() in Configure method of startup class.

Few Built in Middleware’s are

MiddlewareDescription
AuthenticationAdds authentication support.
CORSConfigures Cross-Origin Resource Sharing.
RoutingAdds routing capabilities for MVC or web form
SessionAdds support for user session.
StaticFilesAdds support for serving static files and directory browsing.
DiagnosticsAdds support for reporting and handling exceptions and errors.
Built in Middleware’s

Static Files

By default as ASP.NETCore Application will not serve static files. The default directory for static files is wwwroot, it is built in folder for static files. To serve static files UseStaticFiles() middleware is required. You can create a sub folder under wwwroot for files like css, js etc.

To use the static file middleware call UseStaticFile() Method in configure method of startup class before every thing as follows –

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }

You can also create the sub folders under wwroot folder for css, js and images also.

Default File or Document Middleware

By default asp.net core does not show any default file. If you want to force ASP.NET core to force default file using Default Document Middleware.
Following are the default files –

  • Index.htm
  • Index.html,
  • Default.htm
  • Default.html

To use the default file/document middleware use the method UseDefaultFile() which will inject default file middleware in request pipe line and it will search for a file index.html, index.htm,default.htm, default.html, in wwroot if any of this file is available then it will be get loaded in browser as a default file. You can use default file /document middleware as follows –

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseDefaultFiles(dfo);// use dfo.
            app.UseStaticFiles();
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }

You should remember default files middleware should be injected before StaticFiles middleware and by default it will search for index.htm, index.html, default.htm, default.html. if you want to modify it and make any other file as default document then you can use DefaultFilesOptions. You can modify the default document using default document options as follows –

DefaultFilesOptions options= newDefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("home.html");
app.UseDefaultFiles(options); 

What is Directory Browser Middleware in ASP.NET Core?

If you want to enable the directory browsing in your application we can use the middle ware. For this you can use the UseDictionaryBrower.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

         app.UseDirectoryBrowser(); // show list of directories from app.

            app.UseRouting();
          

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }

Use File Server Middleware

All these three middle wares UseStaticFiles, UseDefaultDocument , UseDirectory browser combined into one middleware called UseFileServer Middleware. You can also define the options to this middle ware using UseFileServerOptions class.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
             FileServerOptions fs = new FileServerOptions();
            fs.DefaultFilesOptions.DefaultFileNames.Clear();
            fs.DefaultFilesOptions.DefaultFileNames.Add("home.html");
            app.UseFileServer(fs);
            app.UseRouting();
             app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }

Leave a Reply