gpt4 book ai didi

c# - 模型在 XML POST 上始终为 null

转载 作者:IT王子 更新时间:2023-10-29 03:55:02 25 4
gpt4 key购买 nike

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

假设我有一个模型:

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

POST 方法是:

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

我使用 header 从 Fiddler 创建请求:

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

和正文:

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

Post 方法中的model 参数始终为null,我不知道为什么。有人知道吗?

最佳答案

两件事:

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

    User-Agent: Fiddler
    Content-Type: application/xml
    Accept: application/xml
  2. Web API 默认使用 DataContractSerializer 进行 xml 序列化。所以你需要在你的 xml 中包含你的类型的命名空间:

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

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

    config.Formatters.XmlFormatter.UseXmlSerializer = true;

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

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

关于c# - 模型在 XML POST 上始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14068288/

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