HttpResponse redirection on remote IIS server generates exception message: "Server cannot set status after HTTP headers have been sent"

StackOverflow https://stackoverflow.com/questions/21288565

سؤال

I have a link inside an email, which when the the user clicks activates their account. The link is Restful and the underlying method implementation is:

public void UserConfirmation(string email)
{
    HttpResponse Response = HttpContext.Current.Response;
    Response.BufferOutput = true;
    Response.StatusCode = 301;
    Response.StatusDescription = "Moved Permanently";
    Response.RedirectLocation = ConfigurationManager.AppSettings["RedirectConfirmationPage"] + "";

    //code to modify user in database (works succesfully)

    Response.Flush();
}

if I run the service from inside visual studio using fiddler, locally, it works. The method is called, the database is updated, and the http response is redirected to a web page.

The problem is if I publish the web app to a remote server (iis 7.5) and run the same method I get a server error status code 504. However the code to modify the database executes, but there is no redirectior

If i look in Trace Viewer I can see an exception with the message "Server cannot set status after HTTP headers have been sent."

هل كانت مفيدة؟

المحلول 2

I replaced the HttpResponse object code with the following static calls and it seems to have fixed the problem

WebOperationContext.Current.OutgoingResponse.Location = ConfigurationManager.AppSettings["RedirectConfirmationPage"] + "";
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.MovedPermanently;

نصائح أخرى

Try this:

public void UserConfirmation(string email)
{
    try
    {
    //code to modify user in database
    }
    catch { }

    string url = ConfigurationManager.AppSettings["RedirectConfirmationPage"];
    HttpContext.Current.Response.RedirectPermanent(url);
}

I think the problem is inside your code to modify user in the database. It crashed and Response.Flush() was not executed.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top