Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET Core 2.0 Static Files

0.00/5 (No votes)
4 Oct 2017 1  
How to serve static content (HTML, CSS, JavaScript, Images) from ASP.NET Core application. Continue reading...

Problem

How to serve static content (HTML, CSS, JavaScript, Images) from ASP.NET Core application.

Solution

Modify the Configure() method in Startup class to use middleware for static files:

public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseStaticFiles(); // for files in wwwroot folder

            app.UseStaticFiles(new StaticFileOptions() // for files in content folder
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "content")),
                RequestPath = new PathString("/outside-content")
            });

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

Add static content to wwwroot and a custom content folder:

Static Files - Explorer

Access the files using site address:

  • http://[site-address]/hello.html
  • http://[site-address]/outside-content/info.html

Discussion

Static files are served, by default, from wwwroot folder and can be accessed as if the content exist in your root folder. The default folder can be changed via WebHostBuilder in Program.cs using:

UseWebRoot("public") // changed wwwroot to public

Static files can also be served from folders outside wwwroot by passing in StaticFileOptions to middleware and setting a FileProvider and RequestPath. This is useful when you want authorized access to files, e.g., by returning FileResult action result from a secure controller.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here