2012-03-28 123 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

相关问题