How to set downloading file name in ASP.NET Web API
In my ApiController class, I have following method to download a file created by server.
public HttpResponseMessage Get(int id)
{
try
{
string dir = HttpContext.Current.Server.MapPath("~"); //location of the template file
Stream file = new MemoryStream();
Stream result = _service.GetMyForm(id, dir, file);
if (result == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
result.Position = 0;
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
return response;
}
catch (IOException)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
Everything is working perfect except that default downloading file name is its id so user might have to type his/her own file name at save as dialog each time. Is there any way to set a default file name in the code above?
Solution 1:
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"
};
Solution 2:
EDIT:
As mentioned in a comment, My answer doesn't account for characters that need to be escaped like a ;
. You should use the accepted answer Darin made if your file name could contain a semi-colon.
Add a Response.AddHeader to set the file name
Response.AddHeader("Content-Disposition", "attachment; filename=*FILE_NAME*");
Just change FILE_NAME to the name of the file.
Solution 3:
If you want to ensure that the file name is properly encoded but also avoid the WebApi HttpResponseMessage you can use the following:
Response.AddHeader("Content-Disposition", new System.Net.Mime.ContentDisposition("attachment") { FileName = "foo.txt" }.ToString());
You may use either ContentDisposition or ContentDispositionHeaderValue. Calling ToString on an instance of either will do the encoding of file names for you.