2016-08-02 79 views
5

所以我測試我的一些路由出去與Postman的,我似乎無法得到這個呼叫通過中間:網頁API可選參數與屬性路由

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 WORKS

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

任何想法,爲什麼我不能用我的前綴和自定義路線之間的可選?我已經嘗試將它們合併到一個自定義路由中,並且不會改變任何內容,任何時候我都會嘗試刪除導致問題的id。

回答

6

可選參數必須在路徑模板結束。所以你想要做的是不可能的。

Attribute routing: Optional URI Parameters and Default Values

你要麼改變你的路線temaple

[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

其實你不需要在路線

[Route("Calls")] 

指定可選參數,或者您需要更改路線

[Route("Calls/{id:int?}/{callId:int?}")] 
public async Task<ApiResponse<object>> GetCall(int? id = null, int? callId = null) 
+0

雖然這可以作爲一個單獨的功能,我期待封裝所有3這些潛在的呼叫在1功能下,如果我理解可選路由權,它應該是可能的。 – tokyo0709

2

我會改變路線到:

[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