【问题标题】:Accessing route and POST params in Web Api 2 Controller Method在 Web Api 2 控制器方法中访问路由和 POST 参数
【发布时间】:2014-09-13 03:03:28
【问题描述】:

我有一个需要访问路由和 POST 正文参数的控制器。但是当我使用这个实现时

public class MessageController : ApiController
{
    [Route( "Data/Message/{apiKey}/{userId}" )] 
    [HttpPost]
    public Message Post( Guid apiKey, string userId, [FromBody] string message)
    {
        // ...
    }
}

message 参数始终为 null

如何访问所有的 apropos 数据?

【问题讨论】:

    标签: c# asp.net-web-api2


    【解决方案1】:

    [FromBody] 参数必须编码为值

    你不要尝试这样做:

    public Message Post( Guid apiKey, string userId, [FromBody] string message)
    {
        // ...
    }
    

    试试这个

     public Message Post( Guid apiKey, string userId, [FromBody] string value)
     {
        // ...
     }
    

    并使用这种代码通过 jquery 进行 POST 请求:

      $.post('YourDomain/Data/Message/{apiKey}/{userId}', { '': value });
    

    更多详情,这里是链接http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

    【讨论】:

    • 谢谢,这澄清了我对 [FromBody] 的困惑。但是,有没有办法在方法参数中混合路由和 POST 数据,例如 public Message Post( Guid apiKey, string userId, Models.Message message),其中 apiKeyuserId 来自路由,message 映射后正文参数?
    • 如何将所有参数包含在一个类中?
    • 好的,所以我实际上试了一下。我急于确认这一点。这不起作用。路由参数不会指向类中的同名属性,更不用说路由参数+后参数了。
    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    相关资源
    最近更新 更多