触发从PageMethod下载.好,不正确的
本文关键字:不正确 下载 PageMethod | 更新日期: 2023-09-27 18:06:23
我试图触发从PageMethod下载XML文件流。我遵循这里的文档
[WebMethod]
public static bool Export()
{
bool successful = false;
try
{
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=Dashboard.xml");
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = true;
SerializableDictionary<string, string> dataToSave = new SerializableDictionary<string, string>();
foreach( var state in StateManager.StateDictionary)
{
var sessionItem = SessionRepository.Instance.GetSession(state.Value);
if (Equals(sessionItem, null)) continue;
using( MemoryStream memoryStream = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(sessionItem.GetType());
serializer.Serialize(memoryStream, sessionItem);
dataToSave.Add(state.Value, Convert.ToBase64String(memoryStream.ToArray()));
}
}
XmlSerializer xmlSerializer = new XmlSerializer(dataToSave.GetType());
using( MemoryStream memoryStream = new MemoryStream())
{
xmlSerializer.Serialize(memoryStream, dataToSave);
HttpContext.Current.Response.AppendHeader("Content-Length", memoryStream.Length.ToString());
memoryStream.Position = 0;
using( StreamReader streamReader = new StreamReader(memoryStream))
{
HttpContext.Current.Response.Write(streamReader.ReadToEnd());
}
}
HttpContext.Current.Response.Flush();
successful = true;
}
catch (Exception exception)
{
_logger.ErrorFormat("Unable to serialize session. Reason: {0}", exception.Message);
}
return successful;
}
没有收到任何警告或错误。刚刚成功完成,没有下载。
编辑:我已经尝试了application/xml和text/plain作为ContentTypes,以及
您需要设置响应头:
Response.AddHeader("content-disposition","attachment; filename=fname.ext")
Response.AddHeader("Content-Length", data.Length.ToString())