Click here to Skip to main content
15,886,873 members
Articles / Web Development / ASP.NET / ASP.NET Core

ASP.NET Core 2.0 Static Files

Rate me:
Please Sign up or sign in to vote.
1.00/5 (3 votes)
4 Oct 2017CPOL 7.6K   1   3
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:

C#
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:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionGood Information Pin
Member 9672022-Jun-18 7:43
Member 9672022-Jun-18 7:43 
General[My vote of 1] This isn't an article Pin
Luka4-Oct-17 23:57
Luka4-Oct-17 23:57 
Same as the previous comment.
This is a tip at best not an article.
GeneralMy vote of 1 Pin
Member 105062271-Sep-17 6:10
Member 105062271-Sep-17 6:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.