When developing an ASP.NET Web API controller method that allows to download a file it is considered a good practice to set
a "Content-Disposition" header to guide a browser of a name of a file being downloaded.
There are two different ways to approach this simple task. First is to add a new HTTP header to the HTTP response using string values
for the header's name and value. The second is to try and use the .NET Framework's infrastructure methods that presumably should make this task easier.
The first method seems to be very simple but potentially dangerous: one would need to hard-code string values and be totally responsible
for the values to be properly formatted according to the W3C standards.
var response = new HttpResponseMessage();
response.Headers.Add("Content-Disposition", "attachment; filename=fileName.ext");
The second method is to try and delegate handling of the specifics of the HTTP protocol to the .NET Framework by using corresponding
presumably built-in methods. This seems more appropriate and even easier to achieve. However due to poor documentation of the Web API extensions
that is easier said than done. without further ado this is how it's done:
var response = new HttpResponseMessage();
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment") { FileName = fileName};
Only one string value here should hard-coded with a guideline available
in the official
documentation so it's not that bad.
If you find this information possible share it with your fellow colleagues so it may save their valuable time.
Alexander Turlov has been working in IT industry since 1987. His programming experience includes such languages as FORTRAN, Pascal, and Basic, C, C++ and C#. He's been working for different industries like science, manufacturing, retail, utilities, finance, insurance, health care, education and so on. His area of interests is rich web applications development with .NET, C#, ASP.NET/MVC and JavaScript. He is working in software development doing architecture, design and development on .NET platform and using Microsoft Visual Studio, IIS and SQL Server as his primary tools, and a lot of other commercial and open source frameworks and tools. He holds a M.Sc. degree in physics and an MCSD.NET certification.
View my profile on LinkedIn
View my blog