RedirectToAction with unknown number of URL variables

677 views Asked by At

I'll preface this with, if you know of a better way to do what I am trying to do, please tell me.

So, I have my login in my Layout (aka MasterPage) so that a user can login no matter what page they are on. (That I want to keep for sure) So, after they login successfully, I want to redirect them back to the page that they were on. I used Request.UrlReferrer.AbsoluteUri to get the URI and parsed out the Controller name and the Action name. A long with the Action name are the unknown number of URL variables, could be none, could be many. So, MVC3 does not like the variables passed along in the Action name. I got around this in other parts of my code by doing:

return RedirectToAction("Message", new { msg = "error" });

But, like I said, I do not know how many variables will be coming in, nor the names of the variables. Any suggestions?

2

There are 2 answers

2
keshav On BEST ANSWER

here is my logon post action. it redirects to the last page the user was on or to the home page if no such url exists

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (MembershipService.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

this part is what you need

        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
            && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
        {
            return Redirect(returnUrl);
        }
        else
        {
            return RedirectToAction("Index", "Home");
        }
0
ScubaSteve On

I found a good way to do this. Since I am already parsing through the URI, I can grab the variables and values, then add them to

RouteValueDictionary queryString = new RouteValueDictionary();

Which I can then pass to:

return RedirectToAction(action, queryString);