在C#中更改资源处理程序的标头中的名称
-
05-07-2019 - |
题
我有一个基于通过查询字符串传递的参数的Response.WriteFile(fileName)资源处理程序。我正确处理mimetype,但问题是在某些浏览器中,文件名出现为Res.ashx(处理程序的名称)而不是MyPdf.pdf(我输出的文件)。有人可以告诉我如何在将文件发送回服务器时更改文件的名称吗?这是我的代码:
// Get the name of the application
string application = context.Request.QueryString["a"];
string resource = context.Request.QueryString["r"];
// Parse the file extension
string[] extensionArray = resource.Split(".".ToCharArray());
// Set the content type
if (extensionArray.Length > 0)
context.Response.ContentType = MimeHandler.GetContentType(
extensionArray[extensionArray.Length - 1].ToLower());
// clean the information
application = (string.IsNullOrEmpty(application)) ?
"../App_Data/" : application.Replace("..", "");
// clean the resource
resource = (string.IsNullOrEmpty(resource)) ?
"" : resource.Replace("..", "");
string url = "./App_Data/" + application + "/" + resource;
context.Response.WriteFile(url);
解决方案
从Joel的评论中延伸出来,你的实际代码看起来像这样:
context.Response.AddHeader("content-disposition", "attachment; filename=" + resource);
其他提示
这个Scott Hanselman的帖子应该有用:
http://www.hanselman.com/blog/CommentView.aspx?guid= 360个
谢谢你们的回答。最终的代码可以工作并检查pdf。
if (extensionArray[extensionArray.Length - 1].ToLower() == "pdf")
context.Response.AddHeader("content-disposition",
"Attachment; filename=" + resource);
不隶属于 StackOverflow