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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With