如何设置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
。
答案 0 :(得分:3)
使用[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);