Search code examples
c#asp.netcookiesauthenticationmobile-safari

C# Login code not work on safari


I used the code below to login to my asp.net website. with framework 4 it's work successfully at web bowers, but didn't work on safari (iphone, ipad) only when I click on login button he refresh the page and not login.

Session["AdminID"] = DT.Rows[0]["Id"].ToString();
Response.Cookies.Add(new HttpCookie("SuperAccountId", DT.Rows[0]["Id"].ToString()));
Response.Cookies["SuperAccountId"].Expires = System.DateTime.Now.AddDays(1);

Response.Cookies.Add(new HttpCookie("SuperAccountName", DT.Rows[0]["Username"].ToString()));
Response.Cookies["SuperAccountName"].Expires = System.DateTime.Now.AddDays(1);
FormsAuthentication.SetAuthCookie(Session["AdminID"].ToString(), true);
FormsAuthentication.RedirectFromLoginPage("admin", true);

//create a cookie
HttpCookie myCookie = new HttpCookie("FirstLoginCookies");

//Add key-values in the cookie
myCookie.Values.Add("first", "1");

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);

if (Request.QueryString["ReturnUrl"] != null)
{
     string redirectURL = Request.QueryString["ReturnUrl"].ToString();
     Response.Redirect("~" + redirectURL);
}
else
{
     Response.Redirect("~/admin");
} 

Solution

  • Make sure you have no error in your master page. (If you are using a master page) Then try editing the last part of your code like below:

                    if (Request.QueryString["ReturnUrl"] != null)
                    {
                        string redirectURL = Request.QueryString["ReturnUrl"].ToString();
                        Response.Redirect("~" + redirectURL, false);
    
                    }
                    else
                    {
                        Response.Redirect("~/admin", false);
                    } 
    

    By setting the second parameter of Response.Redirect to "false" the original page won't be posted back to the browser and you should be redirected to the new page.