Share via


Serve Static files in ASP.NET Core Using Visual Studio 2017

Introduction

This article explains about static files and how to set default page using static files in ASP.NET using Visual Studio 2017 by step by step way. Before reading this article, please read the previous part of this articles at the below link.

Static Files

HTML, CSS, images, JavaScript files are called static files. These files are located in wwwroot folder insight our project. We directly access our static files which are in wwwroot folder, if not in wwwroot we cannot access directly.

Background

Some of the files we need to access directly from one place to another at that time we use wwwroot folder, for example, we wrote common Javascript, CSS, and access to any other project or page those files if placed into wwwroot in our project.

Steps for Creating Static Page

Open New Project

We are using Visual Studio 2017 for developing ASP.NET Core application. Open visual studio and open new project then select the “ASP.NET Core Web Application (.NET Core)”.

We select the “ASP.NET Core 1.1” and select Empty template. An empty project template for creating an ASP.NET Core application. This template does not have any content in it.

Add Static File Packages

In our project, we need to add the Microsoft.AspNetCore.StaticFiles packages in our project to serve the static page in our ASP.Net core applications. Go to solution explorer, right click on our project, and go to Manage NuGet Packages.

In NuGet Package manager, go to browse and type static files in search textbox and we can find the “Microsoft.AspNetCore.StaticFiles” package. Select “Microsoft.AspNetCore.StaticFiles” packages and click the install button on right sight.

 

Select the version 1.1.1 and click install then review changes window will be open and click ok. Now Licenses Acceptance window will be open then click I accept button then installation will be complete.

We can see the package in NuGet inside the Dependencies folder looks like below screenshot.

Add HTML File in wwwroot

We are going to add sample HTML file in wwwroot folder. Go to solution explorer, right click on wwwroot go to Add then go to New Item.
  
Select HTML Page and give page name then click Add button.

We are adding some sample code in Home.html page. We are going to make Hoem.html as a home page using “Microsoft.AspNetCore.StaticFiles” packages.

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title>ASP.NET Core</title>

</head>

<body>

    <h1>Welcome To ASP.NET Core Static Page</h1>

</body>

</html>

Add Code in Startup class

Go to Startup class and enable default file mapping on the current path then enable static file serving for the current path. We need to add following code in startup class at Configure method.

public void Configure(

            IApplicationBuilder app,

            IHostingEnvironment env,

            ILoggerFactory loggerFactory

            )

        {

            loggerFactory.AddConsole();

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }

            //Enables default file mapping on the current path

            DefaultFilesOptions options = new DefaultFilesOptions();

            options.DefaultFileNames.Clear();

            options.DefaultFileNames.Add("Home.html");

            app.UseDefaultFiles(options);

            //Enables static file serving for the current request path

            app.UseStaticFiles();

            app.Run((context) =>

            {

                //await context.Response.WriteAsync("Hello World!");

                throw new Exception();

            });

        }

Now build the ASP.NET Core application and run the application. When we run the application it directly redirects the Home.html page.

Not Directly Redirect Page

If we remove some lines in above-written code from Startup class in configure method, directly page not redirect to the Home.html page. For example, we modified below code in configure method and run the application.

public void Configure(

            IApplicationBuilder app,

            IHostingEnvironment env,

            ILoggerFactory loggerFactory

            )

        {

            loggerFactory.AddConsole();

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }

            app.Run((context) =>

            {

                //await context.Response.WriteAsync("Hello World!");

                throw new Exception();

            });

        }

We get some of the error in output page and we can see the looks like below screenshot.

If enter manually like “http://localhost:53498/home.html” then we getting the same error. Now add single line code from above-written code looks like below.

public void Configure(

            IApplicationBuilder app,

            IHostingEnvironment env,

            ILoggerFactory loggerFactory

            )

        {

            loggerFactory.AddConsole();

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }

            //Enables static file serving for the current request path

            app.UseStaticFiles();

            app.Run((context) =>

            {

                //await context.Response.WriteAsync("Hello World!");

                throw new Exception();

            });

        }

Here we mentioned “app.UseStaticFiles();” . It is denoted enable static file serving for the current request path.  If enter manually like “http://localhost:53498/home.html” after run application it will redirect the home.html page.

If page redirects to the Home.html Page we need to add “app.UseDefaultFiles()” before the “app.UseStaticFiles();”. The UseDefaultFiles() only search on below static file page names like

  1. default.htm
  2. default.html
  3. index.htm
  4. index.html

We are creating different name we need to mention the specifically to UseDefaultFiles(). We can add below code to mention the specific file name.

            //Enables default file mapping on the current path

            DefaultFilesOptions options = new DefaultFilesOptions();

            options.DefaultFileNames.Clear();

            options.DefaultFileNames.Add("Home.html");

            app.UseDefaultFiles(options);

After building and run the code it will be run successfully. Now page automatically redirects to the Home.html  page.

We can download sample project for serve static files in ASP.Net Core in below link. It is help to learn coding level. Sample Download Link

Conclusion        

This article explained about how to serve static files in ASP.Net Core. I hope this article explained very simple way and it is very useful to new learners.