XML POST 上的模型始终为空 [英] Model always null on XML POST

查看:21
本文介绍了XML POST 上的模型始终为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究系统之间的集成,我决定使用 WebApi,但我遇到了一个问题...

I'm currently working on an integration between systems and I've decided to use WebApi for it, but I'm running into an issue...

假设我有一个模型:

public class TestModel
{
    public string Output { get; set; }
}

和POST方法是:

public string Post(TestModel model)
{
    return model.Output;
}

我从 Fiddler 创建了一个带有标题的请求:

I create a request from Fiddler with the header:

User-Agent: Fiddler
Content-Type: "application/xml"
Accept: "application/xml"
Host: localhost:8616
Content-Length: 57

和身体:

<TestModel><Output>Sito</Output></TestModel>

Post 方法中的 model 参数总是 null ,我不知道为什么.有人知道吗?

The model parameter in the method Post is always null and I have no idea why. Does anyone have a clue?

推荐答案

两件事:

  1. 您不需要在内容类型周围加上引号 "" 并在 Fiddler 中接受标题值:

  1. You don't need quotes "" around the content type and accept header values in Fiddler:

User-Agent: Fiddler
Content-Type: application/xml
Accept: application/xml

  • Web API 默认使用 DataContractSerializer 进行 xml 序列化.所以你需要在你的 xml 中包含你的类型的命名空间:

  • Web API uses the DataContractSerializer by default for xml serialization. So you need to include your type's namespace in your xml:

    <TestModel 
    xmlns="http://schemas.datacontract.org/2004/07/YourMvcApp.YourNameSpace"> 
        <Output>Sito</Output>
    </TestModel> 
    

    或者您可以配置 Web API 以在您的 WebApiConfig.Register 中使用 XmlSerializer:

    Or you can configure Web API to use XmlSerializer in your WebApiConfig.Register:

    config.Formatters.XmlFormatter.UseXmlSerializer = true;
    

    那么您的 XML 数据中就不需要命名空间了:

    Then you don't need the namespace in your XML data:

     <TestModel><Output>Sito</Output></TestModel>
    

  • 这篇关于XML POST 上的模型始终为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆