所以我正在使用Postman
测试我的部分路由,似乎无法接听此电话:
API函数
[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工作
http://localhost:61941/api/Employees/1/Calls/1工作
我知道为什么我不能在我的前缀和自定义路由之间使用可选项?我已经尝试将它们组合成一个自定义路线并且不会改变任何东西,任何时候我试图删除它导致问题的id。
答案 0 :(得分:9)
可选参数必须位于路径模板的末尾。所以你想做的事情是不可能的。
Attribute routing: Optional URI Parameters and Default Values
你要么改变自己的路线
[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();
}
}
答案 1 :(得分:3)
我会将路线更改为:
[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
答案 2 :(得分:1)
实际上你不需要在路线
中指定可选参数[Route("Calls")]
或者您需要更改路线
[Route("Calls/{id:int?}/{callId:int?}")]
public async Task<ApiResponse<object>> GetCall(int? id = null, int? callId = null)