2017-05-30 69 views
2

我試圖創建一個像這樣的記載:如何返回createdatroute位置?

[Route("", Name = "CreateAccount")] 
[HttpPost] 
public async Task<IHttpActionResult> CreateAccount([FromBody] JObject account) 
{ 

    var response = await _accountService.Create(account); 

    return CreatedAtRoute(
     routeName: "GetAccount",????); 
} 

記錄的創建成功;然而。我不知道如何返回一個CreatedAtRoute對象?

這是我的GET控制器的方法:

[Route("", Name = "GetAccount")] 
[HttpGet] 
public async Task<IHttpActionResult> GetAccount() 
{ 
    var query = Request.RequestUri.PathAndQuery.Split('/')[2]; 
    var response = _accountService.Get(query); 

    if (!response.Result.IsSuccessStatusCode) 
    { 
     return NotFound(); 
    } 

    var readAsAsync = response.Result.Content.ReadAsAsync<object>(); 
    if (readAsAsync == null) 
    { 
     return NotFound(); 
    } 

    var result = await readAsAsync; 
    return Ok(result); 
} 

正如你所看到的控制器不接受任何參數,而我們得到的參數從Request.RequestUri.PathAndQuery

創建記錄後,我們怎麼樣返回有效的CreatedAtRoute結果?

回答

1

您可以嘗試的一件事是將路由值作爲對象傳遞。框架應該將它們(路由值)轉換爲查詢字符串。

[HttpPost] 
[Route("", Name = "CreateAccount")] 
public async Task<IHttpActionResult> CreateAccount([FromBody] JObject account) { 

    var response = await _accountService.Create(account); 

    var model = await response.Content.ReadAsAsync<MyModel>(); 

    return CreatedAtRoute(
     routeName: "GetAccount", 
     routeValues: new { id = model.Id, name = model.Name }, // can include other properties 
     content: model); 
} 

即應該設置爲位置的標頭中的東西的201響應等

LOCATION: http://localhost/api/accounts?id=5&name=JDoe