【问题标题】:Using both route and POST params in Web Api controller在 Web Api 控制器中同时使用路由和 POST 参数
【发布时间】:2014-11-07 00:26:45
【问题描述】:

如何设置ApiController,以便我可以将方法参数绑定到参数化路由和请求参数(在本例中是 POST,但也可以绑定 PUT)?

类似的东西

public class MessageController : ApiController
{
    public class Message
    {
       public string Content { get; set; }
       public int Priority { get; set; }
    }

    [Route( "Data/Message/{apiKey}/{userId}" )] 
    [HttpPost]
    public Message Post( Guid apiKey, string userId, Message msg)
    {
        // ...
    }
}

这样就可以了

$.post('/Data/Message/<some key>/<some id>', { 
    Content: 'Did you receive my payment?', 
    Priority: 0 
 });

我尝试了Accessing route and POST params in Web Api 2 Controller Method 中使用类并将参数绑定到其属性的方法,但这不起作用。参数总是null。

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api asp.net-mvc-5 asp.net-web-api2 asp.net-web-api-routing


    【解决方案1】:

    使用[FromBody] 属性

    [Route("Data/Message/{apiKey}/{userId})]
    [HttpPost]
    public Message Post(Guid apiKey, string userId, [FromBody] Message msg)
    {
        ...
    }
    

    那么您的 Message 类属性名称应该与您的 javascript 数据对象匹配。

    var data = {
        Content: 'Did you receive my payment?',
        Priority: 0
    };
    
    $.post('/Data/Message/<some key>/<some id>', data);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 2013-05-14
      • 2015-05-04
      • 2016-02-29
      • 1970-01-01
      • 2013-08-25
      • 2020-01-04
      相关资源
      最近更新 更多