ASP.NET MVC4的WebAPI和发布XML数据 [英] ASP.NET MVC4 WebAPI and Posting XML data
问题描述
我错过一招新的WebAPI - 我想通过POST请求提交XML字符串,并没有多少运气
I'm missing a trick with the new webapi - I'm trying to submit an xml string through a post request and not having much luck.
在前端使用jQuery这样的:
The front end is using jQuery like this:
$(document = function () {
$("#buttonTestAPI").click(function () {
var d = " <customer><customer_id>1234</customer_id></customer>";
$.ajax({
type: 'POST',
contentType: "text/xml",
url: "@Url.Content("~/api/Customer/")",
data: d,
success: function (result) {
var str = result;
$("#output").html(str);
}
});
});
});
我的控制器是pretty此刻简单 - 只是默认为后行动 - 试图返回什么传递:
My controller is pretty simple at the moment - just the default for the post action - trying to return what was passed in:
public string Post(string value)
{
return value;
}
不过,价值是反复空。奇怪的是,当我改变我的数据在jQuery来是这样的:
However, "value" is repeatedly null. The odd thing is, when I change my data in the jquery to be something like this:
d = "<customer_id>1234</customer_id>";
然后,我在我的控制器得到价值为1234。
Then I get "value" in my controller as 1234.
怎样才能在我的控制器访问更复杂的XML字符串?
How can I get access to the more complex xml string in my controller?
推荐答案
下面将让你通过POST到Web API方法读取原始XML消息:
The following will allow you to read a raw XML message via a POST to a Web API method:
public void PostRawXMLMessage(HttpRequestMessage request)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(request.Content.ReadAsStreamAsync().Result);
}
您可以调试和检查身体,头部等,并会看到原始的XML发布。我用小提琴手的作曲家做出HTTP POST,这工作得很好。
You can debug and inspect the body, headers, etc. and will see the raw XML posted. I used Fiddler's Composer to make a HTTP POST and this works well.
这篇关于ASP.NET MVC4的WebAPI和发布XML数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!