Friday, February 22, 2019

Adding UseStaticFiles Middleware

The UseStaticFiles is another important middleware which is required to server static HTML, CSS or JavaScript files to the browser. In Asp.Net Core static files are placed in the wwwroot folder. In this example we shall start by adding an index.html file and serve this file to the browser using the UseStaticFiles middleware.

Let us start by adding a static HTML file to the Hello World sample, open the project and right click on the wwwroot folder Add -> New Item, in the list of file types select HTML file, give it a name index.html and create the file. Add some sample text to the file as follows.

<html>
<head>
    <meta charset="utf-8" />
    <title>Hello Static file</title>
</head>
<body>
    Hello from Static file Middleware.
</body>
</html>

Next we will add the UseStaticFiles middleware to the Startup as follows.
namespace HelloAspNet
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseDeveloperExceptionPage();
            app.UseStaticFiles();

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

Build and run the application, by default the text “Hello World” will be printed in the browser, when we change the URL to access the static file index.html the content of the static file will be displayed in the browser.

http://localhost:61978/index.html




Search Flipkart Products:
Flipkart.com

No comments: