2016-08-16 287 views
0

在我的WebAPI中,如果我檢測到錯誤授權,我使用以下;返回401未經授權從WebAPI

[HttpPost] 
    public HttpResponseMessage CustomerQuotationComplete(Guid apiKey, int EnquiryId, int SiteId, bool accepted) 
    { 
     if (IsRequestAuthorized()) 
     { 
     ... 
     } 
     else 
     { 
      var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Bad Authentication" }; 
      throw new HttpResponseException(msg); 
     } 
    } 

但是,我實際上收到302找到的答覆,而不是401未經授權。

那麼我做錯了什麼?

回答

0

嘗試返回你的消息,而不是異常觸發出exeption的:

var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Bad Authentication" }; 
return msg; 
+0

這不一樣的上方。 – Matt

+0

有一個類似的代碼,它確實會返回一個http401。嘗試查看你是否沒有使用任何[全局過濾器或OWIN細節](http://stackoverflow.com/questions/20149750/owin-unauthorised-webapi-call-返回登錄頁面,而不是401)登錄或其他目的,這將被稱爲bedore您的控制器方法。嘗試一個簡單的空項目,以驗證這與你的項目設置有關。 – bsoulier

4

你可以返回未經授權響應

[HttpPost] 
    public IHttpActionResult CustomerQuotationComplete(Guid apiKey, int EnquiryId, int SiteId, bool accepted) 
    { 
     if (IsRequestAuthorized()) 
     { 
     ... 
     } 
     else 
     { 
      return this.Unauthorized(); 
     } 
    } 
+0

很抱歉,您無法將此.Unauthorized(Http.Results.UnauthorisedResult)轉換爲輸入HttpresponseMessage – Matt

+0

請參閱編輯示例。將返回類型更改爲IHttpActionResult –

+0

這也沒有任何區別。它的一切都非常奇怪,必須在項目中保持其他方式,導致意想不到的結果。 – Matt

相關問題