2017-08-07 60 views
1

如果我有控制器GET方法,如:屬性適用於非OK響應

[HttpGet] 
    [Route("accountrecv({accountid})/promisepay", Name = "GetPromisePay")] 
    public HttpResponseMessage GetPromisePay(int accountid) 
    { 
     var query = Request.RequestUri.Query; 
     var uri = new Uri(Client.Instance.BaseAddress.ToString() + accountid + "/promisepay" + query); 
     var request = new HttpRequestMessage { RequestUri = uri, Method = HttpMethod.Get }; 
     var response = Client.Instance.SendAsync(request); 
     return response.Result; 
    } 

我怎樣才能在所有響應,其中HttpStatusCode也不行徵收行爲?

我想我會創造在方法級別的屬性,如:

[NonOKResponse] 
[HttpGet] 
[Route.......] 
public HttpResponseeMessage GetPromisePay(int accountid) 
{ 
//my code 
return response.Result //but force it here to return 404 for EVERY response other than 200 
} 

我如何定義,我可以使用一切又迫使基於一些標準,具體的迴應屬性?

+0

爲什麼不在返回結果前檢查'response'的狀態碼? – maccettura

+0

因爲我有數百個控制器,可能有數千種方法需要應用此行爲 –

+0

實施['IResultFilter'](https://msdn.microsoft.com/en-us/library/system。 web.mvc.iresultfilter(v = vs.118).aspx)在這裏工作? – stuartd

回答

1

我相信this article回答你的問題。您可以使用ExceptionFilterAttribute來處理和管理異常。例如:

public class GeneralExceptionFilterAttribute : ExceptionFilterAttribute 
{ 
    public override void OnException(HttpActionExecutedContext context) 
    { 
     context.Response = new HttpResponseMessage(HttpStatusCode.NotFound); 
    } 
}