2012-03-28 48 views
5

我使用了新的Web API測試版,並希望從我ApiController動作之一返回「發送HTTP標頭後無法重定向。」當返回HttpResponseMessage與HttpStatusCode.Unauthorized

HttpResponseMessage<MyObject>(new MyObject{ MyMessage = "Go Away!" }, HttpStatusCode.Unauthorized)

表單身份驗證劫持響應,崩潰並添加錯誤"Cannot redirect after HTTP headers have been sent.",它是html的響應。

正常抑制技術如this不適用於Web Api。

有沒有人找到解決這個問題的方法?

我看過this forum post人們報告同樣的問題,但那裏的解決方案不適用於這種情況。建議的第一個解決方案使用正常抑制技術,它不適用於web api。第二個使用HttpMessageHandler在請求到達控制器之前攔截請求,我希望控制器正常啓動。

查看DelegatingHandler之後,我可以訪問HttpResponseMessage,但不知道如何處理它以阻止FormsAuth重定向。

+0

解釋爲什麼建議的解決方案不起作用可能對此有所幫助。 – Maurice 2012-03-28 12:50:52

+0

@Maurice好主意,我已經更新了這個問題 – Magpie 2012-03-28 13:33:44

+0

那麼爲什麼像Phil Haack博客文章中提到的那些正常抑制技術呢?它們適用於WebAPI等REST服務。 – Maurice 2012-03-28 14:15:58

回答

2

我使用Phil Haack's SuppressFormsAuthenticationRedirectModule

時所面臨的同樣的問題,我設法通過清除服務器的錯誤如下圖所示

private void OnEndRequest(object source, EventArgs args) 
{ 
    var context = (HttpApplication)source; 
    var response = context.Response; 

    if (context.Context.Items.Contains(SuppressAuthenticationKey)) 
    { 
     context.Server.ClearError(); //Clearing server error 

     response.TrySkipIisCustomErrors = true; 
     response.ClearContent(); 
     response.StatusCode = 401; 
     response.RedirectLocation = null; 
    } 
} 
+1

這對我來說非常適合ASP.NET Web API。我只需要使用'context.Server.ClearError();'我有條件地從我的Global.asax.cs'Application_PostRequestHandlerExecute'方法中調用它。這阻止了ASP.NET在我的JSON響應之後附加重定向HTML。 – 2013-08-21 20:16:31

相關問題