Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static files on asp.net core

I am trying to enable static files on an ASP.NET Core 2.0 web application. I have a bunch of files in a folder called updater which resides outside the wwwroot folder. To allow access to them I added

app.UseStaticFiles(new StaticFileOptions()
{
    ServeUnknownFileTypes = true,
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), @"TestUpdater")
    ),
    RequestPath = new PathString("/Updater")
});

This lets a different program to be able to get its files by calling the urls. The issue is all the files need to be downloaded instead of served. There is one txt file. How do I allow only download instead of it being served?

like image 696
Ratan Avatar asked Jan 01 '26 18:01

Ratan


1 Answers

The only difference between "serving" and "downloading" files as you describe is that in one instance the browser downloads the file to a temporary location and displays it in the window (inline) while the other the browser will ask a user where to save the file to a permanent location (attachment).

If the other programs you're referring to are contacting the server for these files directly it shouldn't matter. For example using HttpClient, you don't have to change your static file middleware at all.

If you want the browser to prompt the user to save the file even if it's a recognized content type, try setting the Content-Disposition response header to "attachment". To do this from your Startup.cs config, modify your StaticFileOptions to use something like this:

new StaticFileOptions()
{
    OnPrepareResponse = context =>
    {
        context.Context.Response.Headers["Content-Disposition"] = "attachment";
    }
}
like image 199
Neil Avatar answered Jan 05 '26 09:01

Neil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!