gpt4 book ai didi

asp.net-mvc - 如何在 MVC 4 Web Api 中接收 XmlDocument?

转载 作者:行者123 更新时间:2023-12-04 05:42:25 25 4
gpt4 key购买 nike

我将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com