在我的简单WebApi项目中,我只使用属性路由:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
}
}
我有这个控制器:
[RoutePrefix("myprefix")]
public class SomeController : ApiController
{
[HttpGet]
[Route("v2/test/dosomething")]
public IHttpActionResult TestIt()
{
return Ok("Test ok");
}
[HttpPut]
[Route("v2/myaction/somethingelse")]
public async Task<IHttpActionResult> MyAction(string message)
{
return Ok("Put ok");
}
}
我正在按如下方式访问上述内容:
GET http://localhost/myapp/myprefix/v2/test/dosomething
PUT http://localhost/myapp/myprefix/v2/myaction/somethingelse
GET
工作正常。但是,PUT
会返回:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost/myapp/myprefix/v2/myaction/somethingelse'.",
"MessageDetail": "No action was found on the controller 'Some' that matches the request."
}
我错过了什么?
答案 0 :(得分:0)
[HttpPut]
[Route("v2/myaction/somethingelse/{message}")]
public async Task<IHttpActionResult> MyAction(string message)
{
return Ok("Put ok");
}
实际上,您还必须在路线中指定参数。
答案 1 :(得分:0)
使用PUT请求发送数据的默认方式是通过正文。所以第一步是在参数的前面添加一个[FromBody]。如果您发送内容类型为json的数据,那么我将创建一个对象作为参数,而不是包含消息参数。
public class jsonMessage
{
public string message {get; set; }
}
使用jsonMessage类作为控制器方法中[FromBody]的参数
[HttpPut]
[Route("v2/myaction/somethingelse")]
public async Task<IHttpActionResult> MyAction([FromBody]jsonMessage message)
{
return Ok("Put ok");
}
然后,当向端点发出请求时,请添加一个请求正文{"message":"waaaasssaaa"}
并将其与Content-Type: 'application/json'