In my ApiController class, I have following method to download a file created by server.
public HttpResponseMessage Get(int id)
{
try
{
strin
If you are using ASP.NET Core MVC, the answers above are ever so slightly altered...
In my action method (which returns async Task<JsonResult>
) I add the line (anywhere before the return statement):
Response.Headers.Add("Content-Disposition", $"attachment; filename={myFileName}");
I think that this might be helpful to you.
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)
Note: The last line is mandatory.
If we didn't specify Access-Control-Expose-Headers, we will not get File Name in UI.
FileInfo file = new FileInfo(FILEPATH);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = file.Name
};
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
You need to set the Content-Disposition
header on the HttpResponseMessage
:
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "foo.txt"
};
This should do:
Response.AddHeader("Content-Disposition", "attachment;filename="+ YourFilename)
Considering the previous answers, it is necessary to be careful with globalized characters.
Suppose the name of the file is: "Esdrújula prenda ñame - güena.jpg"
Raw result to download: "Esdrújula prenda ñame - güena.jpg" [Ugly]
HtmlEncode result to download: "Esdr&_250;jula prenda &_241;ame - g&_252;ena.jpg" [Ugly]
UrlEncode result to download: "Esdrújula+prenda+ñame+-+güena.jpg" [OK]
Then, you need almost always to use the UrlEncode over the file name. Moreover, if you set the content-disposition header as direct string, then you need to ensure surround with quotes to avoid browser compatibility issues.
Response.AddHeader("Content-Disposition", $"attachment; filename=\"{HttpUtility.UrlEncode(YourFilename)}\"");
or with class aid:
var cd = new ContentDisposition("attachment") { FileName = HttpUtility.UrlEncode(resultFileName) };
Response.AddHeader("Content-Disposition", cd.ToString());
The System.Net.Mime.ContentDisposition class takes care of quotes.