Search code examples
c#.netwebmethod

Response.addHeader causes 500 (Internal Server Error)


I have written a Login WebMethod ,if the details are ok i want to redirect to another page.

this is my code :

[WebMethod]
public String Login(String email, String password){

    String result=WSUtils.GetData("check_login", email, password);
    if (result.Equals("True")){

          Context.Response.Clear();
          Context.Response.Status = ""+System.Net.HttpStatusCode.Redirect;
          Context.Response.AddHeader("Location", "/admin/index.html");
          Context.Response.TrySkipIisCustomErrors = true;
          Context.Response.End();

    }
return result;
}

this code causes 500 (Internal Server Error) thank you


Solution

  • Your function is trying to do too much. It is being called as a WebMethod that returns a string, but you are trying to redirect inside it. The problem is that redirecting inside this kind of function doesn't make sense. Whatever called Login only knows about the string result. It could be said that the return type of the function represents a "contract" between the client and the server. By redirecting inside the function you are breaking this contract and doing something unexpected that the client can't interpret, and the server infrastruction that handles the WebRequest can't handle.

    The proper way to do this is to have your Login function stick to the "contract", just return the result. It should be the responsibility of the calling code to interpret the result of that code, by parsing the string result, and taking action on it.

    To do this, remove the entire "if" block from your server call, and change the code on the client to look (something) like this:

    if (myWebServiceClient.Login(email, password) == "True")
    {
        //I logged in, do success stuff here
    }
    else
    {
        //Display some kind of login failed message
        //Redirect here
    }