【问题标题】:XmlDocument downloads with incorrect extension even with Content-Disposition Set即使使用 Content-Disposition Set,XmlDocument 也会以不正确的扩展名下载
【发布时间】:2016-02-12 16:55:20
【问题描述】:

我正在使用一种似乎很标准的方式,使用内存流将 XmlDocument 下载到浏览器:

// Create document and root node
var dashboardXmlDoc = GetXml();

// Download the file
using (MemoryStream xmlMemoryStream = new MemoryStream())
{
    using (XmlWriter writer = XmlWriter.Create(xmlMemoryStream))
    {
        writer.Flush();
        dashboardXmlDoc.WriteTo(writer); // Write to memorystream
    }

    byte[] data = xmlMemoryStream.ToArray();
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("Content-Disposition:", "filename=samplefile.xml");
    HttpContext.Current.Response.AppendHeader("Content-Length", data.Length.ToString());
    HttpContext.Current.Response.ContentType = "application/octet-stream";

    HttpContext.Current.Response.BinaryWrite(data);
    HttpContext.Current.Response.End();
}

似乎一切正常,除了文件没有指定的名称或扩展名...它以与运行此代码的 .apsx.cs 对应的 .apsx 页面命名。

在某些方面与本案非常相似:

Change name of file sent to client?

虽然我正在使用内存流并处理 XML,并且已经设置了 Content-Disposition,所以给定的修复在这里不起作用(除非我以某种方式错误地做错了?)

我已经能够让 XML 文档在浏览器中打开,但我认为这里必须有可能获得正确的文件名和扩展名。

我尝试将 ContentType 更改为“text/xml”,并尝试使用和不使用“attachment;”在 Content-Disposition 标头的文件名参数之前。

如果我可以提供更多代码或检查任何内容,请告诉我!

【问题讨论】:

  • 您能否尝试从content-disposition 标头名称中删除冒号: 是否可以解决问题?

标签: c# .net download xmldocument memorystream


【解决方案1】:

为了解决这个问题,我建议采取以下步骤(那些对我有用):

  • 删除Content-Disposition 标头名称中的冒号:
  • Content-Disposition 标头值中使用attachment
  • 将内容类型更改为text/xml

示例:

HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=samplefile.xml");
// ...
HttpContext.Current.Response.ContentType = "text/xml";

【讨论】:

  • 感谢@Markus 做到了。我猜它一定是那个冒号?
  • @GP24:是的,很可能。在看了足够长的代码之后很容易错过 :-)
猜你喜欢
  • 2013-10-15
  • 2016-03-23
  • 2013-12-06
  • 2015-05-27
  • 1970-01-01
  • 2013-08-03
  • 1970-01-01
  • 2021-12-01
  • 2018-11-26
相关资源
最近更新 更多