Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot redirect after HTTP headers have been sent." When returning HttpResponseMessage with HttpStatusCode.Unauthorized

I'm using the new Web Api beta and wish to return

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

from one of my ApiController actions.

Forms Authentication hijacks the response, crashes and adds the error "Cannot redirect after HTTP headers have been sent." and it's html to the response.

Normal suppression techniques like this don't work with Web Api.

Has anyone found a work around to this?

I've looked at this forum post where people report the same problem but the solutions there don't work for this case. The first solution suggested uses the normal suppression technique which doesn't work for web api. The second uses a HttpMessageHandler to intercept the request before it gets to the controller, I want the controller to fire as normal.

After looking into the DelegatingHandler I can get access to the HttpResponseMessage but have no idea what to do with it to stop FormsAuth from redirecting.

like image 259
Magpie Avatar asked Nov 05 '22 03:11

Magpie


1 Answers

I faced the same issue when using the Phil Haack's SuppressFormsAuthenticationRedirectModule

I managed to fix it in my case by clearing the server's error as shown below

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;
    }
}
like image 75
Julien Jacobs Avatar answered Nov 09 '22 06:11

Julien Jacobs