我遵循@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());
and below my We BAPI控制器:
public HttpResponseMessage Post(XDocument xml)
{
return Request.CreateResponse(HttpStatusCode.OK, xml);
}
它不是MVC控制器,它apicontroller,並且在這之後http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api- that-supports-crud-operations沒有必要添加[HttpPost]屬性。而且在你的例子中xml也是null。 – Rhot