ASP.NET Web API - 模型绑定不在POST上使用XML数据

Ski*_*ris 10 asp.net-web-api

在使用ASP.NET Web API使用XML数据进行POST时,我无法使模型绑定工作.JSON数据工作正常.

使用全新的Web API项目,这是我的模型类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class PostResponse
{
    public string ResponseText { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我在控制器中的post方法:

    public PostResponse Post([FromBody]Person aPerson)
    {
        var responseObj = new PostResponse();
        if (aPerson == null)
        {
            responseObj.ResponseText = "aPerson is null";
            return responseObj;
        }

        if (aPerson.FirstName == null)
        {
            responseObj.ResponseText = "First Name is null";
            return responseObj;
        }

        responseObj.ResponseText = string.Format("The first name is {0}", aPerson.FirstName);
        return responseObj;
    }
Run Code Online (Sandbox Code Playgroud)

我可以使用Fiddler的JSON成功运行它:

请求标题:
用户代理:Fiddler
主机:localhost:49188
内容类型:application/json; charset = utf-8
内容长度:38

请求正文:
{"FirstName":"Tom","LastName":"Jones"}

结果:
{"ResponseText":"名字是汤姆"}

传递XML时,Person对象没有正确补充水分:

请求标题:
User-Agent:Fiddler
主机:localhost:49188
内容类型:text/xml
内容长度:79

请求正文:
<Person>
    <FirstName> Tom </ FirstName>
    <LastName> Jones </ LastName>
</ Person>

结果:
<ResponseText> aPerson为空</ ResponseText>

根据我的理解,XML应该与JSON类似.关于我在这里缺少什么的任何建议?

谢谢,
跳过

Fil*_*p W 25

将此添加到您的WebApiConfig.cs:

config.Formatters.XmlFormatter.UseXmlSerializer = true;
Run Code Online (Sandbox Code Playgroud)

这迫使Web API使用XMLSerializer而不是DataContractSerializer,并允许您传递原始XML.

否则你必须传递完全限定数据的XML,即:

<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Test.WebAPI.Controllers">
<FirstName>a</FirstName>
<LastName>b</LastName>
</Person> 
Run Code Online (Sandbox Code Playgroud)

  • 对于仍然获得空模型的人来说,找出错误的提示只是通过Request.Content.ReadAsStringAsync()抓取请求内容并尝试使用XmlSerializer自行反序列化XML.如果出现问题,而不是像Web API一样返回null,XmlSerializer将抛出一个异常,告诉你为什么它不能反序列化.在我的例子中,这就是我发现我的XML声明声明UTF-16编码而请求本身是UTF-8编码的方式.这是我从未想过的事情,而不仅仅是自己进行反序列化. (2认同)
  • +1 @Bas - 几乎为我工作.我不得不想要这样做:Request.Content.ReadAsStreamAsync().Result.Seek(0,System.IO.SeekOrigin.Begin); string result = Request.Content.ReadAsStringAsync().Result; (2认同)