开发者

ASP.NET MVC Membership: Who should provide "returnUrl" to the LogOn method?

Here's the definition of the LogOn post action method

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
  // more inside
}

I've a basic question. Doe开发者_C百科s the framework supplies the string returnUrl? or I do have that responsibility?

Thanks for helping.


It depends on who is calling this method and whether this parameter is supplied in the POST request. For example if the user tries to access a controller action decorated with the [Autorize] attribute and he is not authenticated the framework will automatically redirect to the LogOn action (the one that renders the form, not the one with [HttpPost]) and supply the returnUrl parameter. Then you could have a hidden field in the logon form to persist its value so that when the user enters his credentials and submits the form to the LogOn action, in case of successful login, he is redirected to the initially requested page.


Well, as I do sometimes, I answer my own question to add more information on how I resolved a problem after getting other people answer (In this case, Darin Dimitrov).

Briefly, @Darin Dimitrov explained to me that I need to supply the returnUrl if the redirection to LogOn action method is not the result of forcing a user to supply credentials (when the method is trying to access is decorated with a [Authorize] attribute). I need to use new { returnUrl = RouteData.Values["action"] } to supply that value.

Here are some problems:

  1. Intellisense did not recognize ``RouteData.Values["action"], I needed to use Page.RouteData.Values["action"]

  2. I kept getting the following error: "the resource cannot be found", url showing http://example.com/Account/Whatever_action_is_in_the_returnUrl. That make sense because I did only supply the action string.

  3. I did this

    new
    {
        returnUrl = Page.RouteData.Values["controller"] + "/" + Page.RouteData.Values["action"]
    } 
    

    But I got the some error:"the resource cannot be found", url showing http://example.com/Account/myController/myAction. The account was still in the Url, causing the same error.

  4. Finally, I added an other slash in the beginning then it worked.

    new
    {
        returnUrl = "/" + Page.RouteData.Values["controller"] + "/" + Page.RouteData.Values["action"]
    } 
    

It looks like it's important to know many faces of the the redirections business. So far, I've mostly used RedirectToAction().

Thanks @Darin Dimitrov.


Try putting the following in the View that is providing the LogOn

@using (Html.BeginForm("index", "signin", new { ReturnUrl = Request.QueryString["ReturnUrl"] }))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜