2012-08-07 25 views
1

雖然在ResponseFilters中有無論如何獲取返回給客戶端的狀態碼(和描述)?在ServiceStack ResponseFilter中可以獲取HttpStatusCode嗎?

長的解釋: 我正在尋找添加一個響應頭,而我在一個響應過濾器。問題是在我們的API中我們設置了一些NotFound & BadRequest在狀態描述中爲用戶返回一條消息;

return HttpError.NotFound(string.Format("Not found with TicketCodeId {0}", 
     request.TicketCodeId)) 

這在各種android和.net客戶端很好用。 但一些客戶端(我在看你的iPhone)沒有得到狀態描述。我們的想法是在響應過濾器中看到狀態碼設置爲400範圍,並且它有一個特殊的消息,然後添加一個頭並將狀態消息描述複製到其中。

問題是ResponseFilter有權訪問IHttpResponse,並且該對象只有一個setter到狀態碼(因此我無法確定是否需要添加標頭)。

我想用這種通用的方式來解決這個問題,以避免必須記住(並回顧所有的服務實現),無論哪裏都設置了一個400狀態碼來將相同的描述添加到標題中。如果這是在一個單獨的地方,ResponseFilter完成,那將會很好。

ResponseFilter documentation

回答

1

因爲我們正在返回與錯誤請求和NOTFOUND其中我們在狀態描述爲或者引發HTTPError或HttpResult(兩者都是類型IHttpResult的)使用消息我可以執行以下操作來創建所有響應期望的額外的標頭:

// Add Filter: If result is of type IHttpResult then check if the statuscode 
// is 400 or higher and the statusdescription is set. 
this.ResponseFilters.Add((req, res, dto) => 
{ 
    if (dto == null) return; 

    var httpResult = dto as IHttpResult; 
    if (dto is IHttpResult) 
    { 
     // If statuscode is 400 then add a Header with the error message; 
     // this since not all clients can read the statusdescription 
     if ((int)httpResult.StatusCode >= 400) 
      AddPmErrorMessageHeader(res, httpResult.StatusDescription); 
    } 
}); 

的AddPmErrorMessageHeader方法會做一些額外的驗證和使用RES要添加的對象頭:

res.AddHeader("PmErrorMessage", statusDescription); 

我使用res.OriginalResponse做了一些測試,但總是將StatusCode設置爲200,即使在設置4 **狀態代碼之前也是如此。

相關問題