Web Api可选参数位于中间,带有属性路由

tok*_*709 8 c# asp.net asp.net-mvc-routing asp.net-web-api

所以我正在测试我的一些路由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();
    }
}
Run Code Online (Sandbox Code Playgroud)

邮差要求

http:// localhost:61941/api /员工/电话不工作

错误:

{
  "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."
}
Run Code Online (Sandbox Code Playgroud)

http:// localhost:61941/api/Employees/1/Calls WORKS

http:// localhost:61941/api/Employees/1/Calls/1 WORKS

知道为什么我不能在我的前缀和自定义路线之间使用可选项吗?我已经尝试将它们组合成一个自定义路线并且不会改变任何东西,任何时候我试图删除它导致问题的ID.

Nko*_*osi 9

可选参数必须位于路径模板的末尾.所以你想做的事情是不可能的.

属性路由:可选URI参数和默认值

你要么改变你的路线temaple

[Route("Calls/{id:int?}/{callId:int?}")]
Run Code Online (Sandbox Code Playgroud)

或创建一个新的动作

[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();
    }
}
Run Code Online (Sandbox Code Playgroud)