[英]Web Api Optional Parameters in the middle with attribute routing
所以我正在用Postman
测试我的一些路由,但我似乎无法通过这个电话:
接口函数
[RoutePrefix("api/Employees")]
public class CallsController : ApiController
{
[HttpGet]
[Route("{id:int?}/Calls/{callId:int?}")]
public async Task<ApiResponse<object>> GetCall(int? id = null, int? callId = null)
{
var testRetrieve = id;
var testRetrieve2 = callId;
throw new NotImplementedException();
}
}
邮递员请求
http://localhost:61941/api/Employees/Calls 不起作用
错误:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:61941/api/Employees/Calls'.",
"MessageDetail": "No action was found on the controller 'Employees' that matches the request."
}
http://localhost:61941/api/Employees/1/Calls WORKS
http://localhost:61941/api/Employees/1/Calls/1 WORKS
知道为什么我不能在前缀和自定义路由之间使用可选项吗? 我试过将它们组合成一个自定义路由,这不会改变任何东西,任何时候我试图删除它都会导致问题的 id。
可选参数必须在路由模板的末尾。 所以你试图做的事情是不可能的。
你要么改变你的路线模板
[Route("Calls/{id:int?}/{callId:int?}")]
或创建一个新动作
[RoutePrefix("api/Employees")]
public class CallsController : ApiController {
//GET api/Employees/1/Calls
//GET api/Employees/1/Calls/1
[HttpGet]
[Route("{id:int}/Calls/{callId:int?}")]
public async Task<ApiResponse<object>> GetCall(int id, int? callId = null) {
var testRetrieve = id;
var testRetrieve2 = callId;
throw new NotImplementedException();
}
//GET api/Employees/Calls
[HttpGet]
[Route("Calls")]
public async Task<ApiResponse<object>> GetAllCalls() {
throw new NotImplementedException();
}
}
我会将路线更改为:
[Route("Calls/{id:int?}/{callId:int?}")]
并将[FromUri]
属性添加到您的参数中:
([FromUri]int? id = null, [FromUri]int? callId = null)
我的测试函数如下所示:
[HttpGet]
[Route("Calls/{id:int?}/{callId:int?}")]
public async Task<IHttpActionResult> GetCall([FromUri]int? id = null, [FromUri]int? callId = null)
{
var test = string.Format("id: {0} callid: {1}", id, callId);
return Ok(test);
}
我可以使用以下方法调用它:
https://localhost/WebApplication1/api/Employees/Calls
https://localhost/WebApplication1/api/Employees/Calls?id=3
https://localhost/WebApplication1/api/Employees/Calls?callid=2
https://localhost/WebApplication1/api/Employees/Calls?id=3&callid=2
实际上你不需要在路由中指定可选参数
[Route("Calls")]
或者你需要改变路线
[Route("Calls/{id:int?}/{callId:int?}")]
public async Task<ApiResponse<object>> GetCall(int? id = null, int? callId = null)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.