2013-09-27 25 views
5

有沒有一種方法可以指定Web API控制器中某個方法的成功返回碼?ASP.NET Web API控制成功代碼(200與201)

我最初的控制器是結構如下圖所示

public HttpResponseMessage PostProduct(string id, Product product) 
{ 
var product= service.CreateProduct(product); 
return Request.CreateResponse(HttpStatusCode.Created, product); 
} 

然而,有缺點,當你生成Web API幫助頁面上面的方法。 Web API幫助頁面API不能自動解碼強類型Product是響應,因此在其文檔中生成示例響應對象。

所以我採用下面的方法,但這裏的成功代碼是OK (200)而不是Created (201)。無論如何,我可以使用一些屬性風格的語法來控制方法的成功代碼?此外,我還想將位置標題設置爲創建資源可用的URL - 同樣,在處理HttpResponseMesage時,這很容易實現。

public Product PostProduct(string id, Product product) 
{ 
var product= service.CreateProduct(product); 
return product; 
} 

回答

3

關於下面的觀察:

However, there is drawback to the above approach when you generate Web API help pages. The Web API Help page API cannot automatically decode that the strongly typed Product is the response and hence generate a sample response object in its documentation.

你可以看看的是它和HelpPage包安裝HelpPageConfig.cs文件。它恰好適用於像您這樣的場景,您可以設置響應的實際類型。

在Web API的最新版本(5.0 - 當前RC)中,我們引入了一個名爲ResponseType的屬性,您可以使用該屬性來修飾實際類型的操作。你可以在你的場景中使用這個屬性。

+0

謝謝,這工作。是的,將很高興與屬性路由一起裝飾它,而不必在不同的地方編寫相同的映射。很高興知道它在下一個版本中的出現。 – govin

+0

嗨,在即將發佈的Web API中,是否還會有一條規定,指定SuccessResponseType和ErrorResponseType以及可能的狀態碼列表 - 以便我可以在API文檔中捕獲這些代碼? – govin

1

我這樣做:

[HttpGet] 
public MyObject MyMethod() 
{ 
    try 
    { 
     return mysService.GetMyObject() 
    } 
    catch (SomeException) 
    { 
     throw new HttpResponseException(
      new HttpResponseMessage(HttpStatusCode.BadRequest) 
       { 
        Content = 
         new StringContent("Something went wrong.") 
       }); 
    } 
} 

如果你沒有得到你所期望的,拋出一個HttpResponseException。

相關問題