Redirect(url) not redirecting

528 Views Asked by At

I have a simple login screen in .Net MVC. I use Redirect() method to redirect to the given url after succesful login, but Redirect(url) does not get anywhere, the page remains in the login screen.

Below link gets returnurl fine: @Html.ActionLink("Buy","Login","Account",new { returnUrl = Request.RawUrl })

Then in the login screen, returnUrl shows this url: http://localhost:1820/Account/Login?returnUrl=%2FBasket%2FGoToShopCart

Redirect(url) which is not redirecting:

[HttpPost]
public ActionResult Login(Login l, string returnurl)
{
      RegisteredCustomer rc = new RegisteredCustomer();
      string url = "";
      Repository r = new Repository();
      var obj = r.GetUser(l);
      if (obj != null)
      {
          Session["UserID"] = obj.RegisterID.ToString();
          url = returnurl;
      }
      else
          url ="/Account/Login";
      return Redirect(url);
}`

And I pass url to HttpPost method here in login View:

`@using (Html.BeginForm("Login", "Account", new { returnUrl = Request.QueryString["ReturnUrl"] }, FormMethod.Post))
{
        @Html.Hidden("returnUrl", ViewContext.HttpContext.Request.Url.PathAndQuery)
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        ...
        <input type="submit" value="Enter" />

}`

Also it is not redirecting this url neither :

http://localhost:1820/Account/Login

I have checked these answers but couldn't help me:

Redirect to returnURL not working Redirect request to 'ReturnUrl' displays Login Page

2

There are 2 best solutions below

1
Nguyễn Xuân Quang On

You can use return RedirectToAction("Login","Account");

0
bujari On

As I can see the url needs to be properly constructed. The answer from @NKosi at https://stackoverflow.com/a/44837491/5770686 I belive can help you, and also using other Redirect methods like RedirectToAction, RedirectToRoute etc. (https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.redirect?view=aspnet-mvc-5.2)