C# web api下载xml+;HttpResponseMessage
我使用WebAPI返回xml文件中的项目列表。它起作用了 这是我的方法:C# web api下载xml+;HttpResponseMessage,c#,xml,asp.net-web-api,C#,Xml,Asp.net Web Api,我使用WebAPI返回xml文件中的项目列表。它起作用了 这是我的方法: /// <summary> /// Gets the product by division identifier. /// </summary> /// <param name="id">The div identifier.</param> /// <param name="userId">The user identifier.</param>
/// <summary>
/// Gets the product by division identifier.
/// </summary>
/// <param name="id">The div identifier.</param>
/// <param name="userId">The user identifier.</param>
/// <returns>A Xml file flow</returns>
[ActionName("Divisionxml")]
public HttpResponseMessage GetProductByDivisionIdXml(int id, int userId)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
var adoria = new Adoria(....);
var serializer = new XmlSerializer(typeof (Adoria));
var builder = new StringBuilder();
using (var writer = new StringWriter(builder))
{
serializer.Serialize(writer, adoria);
result.Content = new StringContent(builder.ToString(), Encoding.UTF8, "application/xml");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName =
string.Format("export_product_{0}.xml", id)
};
return result;
}
return new HttpResponseMessage();
}
//
///按部门标识符获取产品。
///
///div标识符。
///用户标识符。
///Xml文件流
[ActionName(“Divisionxml”)]
公共HttpResponseMessage GetProductByDivisionIdXml(int-id,int-userId)
{
var结果=新的HttpResponseMessage(HttpStatusCode.OK);
var adoria=新adoria(…);
var serializer=新的XmlSerializer(typeof(Adoria));
var builder=新的StringBuilder();
使用(var writer=newstringwriter(生成器))
{
序列化程序。序列化(作者,adoria);
result.Content=newstringcontent(builder.ToString(),Encoding.UTF8,“application/xml”);
result.Content.Headers.ContentDisposition=新的ContentDispositionHeaderValue(“附件”)
{
文件名=
格式(“导出产品”{0}.xml”,id)
};
返回结果;
}
返回新的HttpResponseMessage();
}
xml文件由浏览器上载和自动下载。美好的
但是在这个exml文件中有第一行:
<?xml version="1.0" encoding="utf-16"?>
我不知道为什么。我允许直接在浏览器上显示,但这一行不显示
您有什么建议吗?这就是众所周知的
Xml声明
——正如您所看到的,它定义了所使用的编码和版本——通常您希望保留它——它不会影响文档内容。您可以在序列化过程中删除它,例如,感谢它的工作。我使用一个新的XmlWriterSettings{Encoding=Encoding.UTF8,Indent=true,ommitXMLDeclaration=ommitXMLDeclaration};可能重复返回新的HttpResponseMessage();这一行在代码中是多余的。它永远不会被称为。