Web Api可选参数位于中间,具有属性路由
本文关键字:中间 路由 属性 Api 参数 于中间 Web | 更新日期: 2023-09-27 17:59:55
所以我正在用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都会引起问题。
可选参数必须位于路由模板的末尾。所以你想做的是不可能的。
属性路由:可选URI参数和默认值
您可以更改路线模板
[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)