How do I specify a return url for a link to the login form?

馋奶兔 提交于 2019-12-02 17:21:04

The solution is to use HttpContext.Current.Request.RawUrl like this:

<%= Html.ActionLink("log on", "LogIn", new { controller = "User", returnUrl = HttpContext.Current.Request.RawUrl }) %>

Or with an extension method from MVC futures (Microsoft.Web.Mvc.dll):

<%= Html.ActionLink<AccountController>(c => c.LogOn("name", "password", false, HttpContext.Current.Request.RawUrl), "login here")%>

ActionController is the default one in mvc but just add returnUrl to your own.

One way would be to build the links that send the user to the login form, with returnUrl=/PageToReturnTo (<a href="/Account/Login/?returnUrl=/Product/10">Login</a> for example). You'd want to write it so the return url was constructed from your routes though, manually writing those links on every page could be cumbersome.

The default login action in MVC has the returnUrl functionality already built. Just need to pass it a value and it will do the rest. Here's a copy'n paste of the method signature from a fresh project.

public ActionResult Login(string username, string password, bool rememberMe, string returnUrl)

Hope that helps ya!

You can use Page.Request.Url to get the route that resulted in the currently rendered view.

Though that's more of a cosmetic detail, you might want to unify the requests that came through the '/' and '/default.aspx' routes and always return to the '/' route. I have a helper property in my master page that does exactly that.

    protected Uri RouteUrl
    {
        get
        {
            if (Page.Request.Url.AbsolutePath.StartsWith("/default.aspx", StringComparison.OrdinalIgnoreCase))
            {
                return new Uri(Request.Url, new Uri(Response.ApplyAppPathModifier("~/")));
            }

            return Page.Request.Url;
        }
    }

I don't know about ASPX, but there are a couple of problems we encountered building this:

When the user gets their password wrong, and loops-round the Login page to have another go, the Target must still be preserved.

We also decided to preserve POST variables to a page that then required the just-in-time login

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!