As.Net core tutorials

Updated : Mar 29, 2020 in Articles

How to access static the files in asp.net core 404 error

this tutorial we will learn about how to access static the files in asp.net core 404 error like Images, CSS, Jquery, Documents formate and Static Html page in asp.net core

Server files inside of webroot

In asp.net core all static files in under wwwroot by default.

Asp.net core it is not possible to access the static files by default like CSS,js, images it will show you the error 404

you need to request to the middleware like app.UseStaticFiles();

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();
}

read files outside of webroot through  StaticFileOptions

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); 
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "YouStaticFolderName")),
        RequestPath = "/StaticFiles"
    });
}

In the above code, the YouStaticFolderName path hierarchy is public via the StaticFiles URI segment

you are request to http://<your _server_address>/StaticFiles/images/download.jpg

<img src="~/StaticFiles/images/download.jpg" alt="ASP.NET" class="img-responsive" />

Set HTTP response headers through StaticFileOptions

for the image, cache files have been made publicly cacheable for 600 seconds in the Development environment section

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var cachePeriod = env.IsDevelopment() ? "600" : "604800";
    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = ctx =>
        {           
            ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
        }
    });
}

the above all static directory is publicly accessed it means there is no authorization  for restricting the static files

Static file authorization

Asp.net core under wwwroot all files are public accusable if you are the request through app.UseStaticFiles() middleware

so we want to restrict the file follow the given below code

[Authorize]
public IActionResult BannerImage()
{
    var file = Path.Combine(Directory.GetCurrentDirectory(), 
                            "YouStaticFolderName", "images", "download.jpg");

    return PhysicalFile(file, "image/svg+xml");
}

Using UseFileServer Middleware

Asp.net core UseFileServer Middleware is a combine of the functionality of UseStaticFilesUseDefaultFiles in this case

Asp.net core UseFileServer Middleware enables the serving of static files and the default file

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); 

    app.UseFileServer(new FileServerOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "YouStaticFolderName")),
        RequestPath = "/StaticFiles",
        EnableDirectoryBrowsing = true
    });
}

UseFileServer Middleware DirectoryBowsing isn’t enabled you to need to set the property value is true

public void ConfigureServices(IServiceCollection services)
{
    services.AddDirectoryBrowser();
}

Accessing the files through FileExtensionContentTypeProvider

Set up custom content types – associating file extension to MIME type

public void Configure(IApplicationBuilder app)
{
    var provider = new FileExtensionContentTypeProvider();
    // Add new mappings file
    provider.Mappings[".myapp"] = "application/x-msdownload";
    provider.Mappings[".htm3"] = "text/html";
    provider.Mappings[".image"] = "image/png";
    // Replace an existing mapping files
    provider.Mappings[".rtf"] = "application/x-msdownload";
    // Removing MP4 videos.
    provider.Mappings.Remove(".mp4");

    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),
        RequestPath = "/Images",
        ContentTypeProvider = provider
    });
}

SandeepMVN
Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Austin Oyen
Austin Oyen
April 16, 2020 10:56 pm

First time visiting your website, I love your site!

1
0
Would love your thoughts, please comment.x
()
x