【问题标题】:Web API POST not bindingWeb API POST 未绑定
【发布时间】:2014-10-24 04:06:54
【问题描述】:

我有一个 SpecialRequest 类,里面只有一个键。

public class SpecialRequest
{
    public string Key { get; set; }
}

一个简单的控制器

public class ValuesController : ApiController
{
    // GET api/values
    public SpecialRequest Get()
    {
        return new CodeRequest {SecretKey = "ABSDCV"};
    }

    // POST api/values
    public string Post(SpecialRequest specialRequest)
    {
        string temp = specialRequest.Key + "-TESTING";
        return temp;
    }
}

使用提琴手我 POST 到 Post,我可以看到它在调试器中被击中,但 POST 的主体未绑定到 Post 方法中的 specialRequest 参数。

Fiddler Headers :
User-Agent: Fiddler
Host: localhost:64180
Content-Length: 66
Content-Type: text/xml


Request Body:
<CodeRequest>
   <SecretKey>
      Hello 
   </SecretKey>
</CodeRequest>

我忘了做什么?

【问题讨论】:

    标签: post binding asp.net-web-api fiddler


    【解决方案1】:

    1- 您需要将 [FromBody] 添加到您的方法参数中。

    // GET api/values/5
    public SpecialRequest Get(int id)
    {
        return new SpecialRequest {Key = "ABC-Key"};
    }
    
    // POST api/values
    [HttpPost]
    public void Post([FromBody]SpecialRequest specialRequest)
    {
        specialRequest.Key += "Testing";
        // Do something
    }
    

    2- 您的请求/内容类型应该是正确的 xml:

    我。内容类型应为 "Content-Type: application/xml" 而不是 text/xml。

    二。正文应该是:

    <SpecialRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebApplication2.Controllers">
        <Key>ABC-Key</Key></SpecialRequest>
    

    这肯定会解决它。

    希望对您有所帮助。

    编辑 只需确保更改传递的 xml 中的命名空间以匹配您的项目命名空间,因此在这种情况下我的命名空间是 WebApplication2.Controllers,请确保将其更改为您的控制器命名空间。

    【讨论】:

    • 那么你正在其他地方做其他事情,这会阻止这个工作,因为我有一个工作演示,我从中发布了这个代码,除了定义 SpecialRequest 类之外我没有做太多,然后定义方法,如您在上面看到的,最后运行应用程序并使用提琴手我使用 Post 与上面的正文完全相同,您唯一需要更改的是 xmlns 字符串中的名称空间以匹配您的应用程序名称空间?让我知道你发生了什么事。
    猜你喜欢
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多