我正在将 XmlDocument 发布到 ApiController(来自 Windows 服务,服务工作正常,发布正确,我在 wcf web api 中使用它),但 xml 始终为空,我做错了什么? 我可以发布一些类(class),例如教程,或者获取任何数据,一切都会好的,但我无法发布 XmlDocument。
public class XmlController : ApiController
{
public void PostXml(XmlDocument xml)
{
// code
}
}
最佳答案
我遵循@Rhot给出的解决方案,但不知何故它不起作用,所以我像下面这样编辑,这对我有用:
public class XmlMediaTypeFormatter : MediaTypeFormatter
{
public XmlMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
}
public override bool CanReadType(Type type)
{
return type == typeof(XDocument);
}
public override bool CanWriteType(Type type)
{
return type == typeof(XDocument);
}
public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
{
var reader = new StreamReader(stream);
string value = reader.ReadToEnd();
var tcs = new TaskCompletionSource<object>();
try
{
var xmlDoc = XDocument.Parse(value);
tcs.SetResult(xmlDoc);
}
catch (Exception ex)
{
//disable the exception and create custome error
//tcs.SetException(ex);
var xml = new XDocument(
new XElement("Error",
new XElement("Message", "An error has occurred."),
new XElement("ExceptionMessage", ex.Message)
));
tcs.SetResult(xml);
}
return tcs.Task;
}
public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)
{
var writer = new StreamWriter(stream);
writer.Write(((XDocument)value).ToString());
writer.Flush();
var tcs = new TaskCompletionSource<object>();
tcs.SetResult(null);
return tcs.Task;
}
}
注册到global.asax:
GlobalConfiguration.Configuration.Formatters.Insert(0, new XmlMediaTypeFormatter());
在我的 WebAPI Controller 下面:
public HttpResponseMessage Post(XDocument xml)
{
return Request.CreateResponse(HttpStatusCode.OK, xml);
}
关于asp.net-mvc - 如何在MVC 4 Web Api中接收XmlDocument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11120872/