Alexander Efimov
Alexander Efimov

Reputation: 2687

How to eliminate ReturnUrl from the browser address

Now on unauthorized attempt to access an action my ASP.NET MVC app redirects user to the login page and generates URL shown below:

http://www.mysite.com/Account/Log?ReturnUrl=%2Ftest%2Fsampleaction

So, is there a way to eliminate this string from the URL, but to save it somewhere to be able to redirect user back after login?

Upvotes: 2

Views: 923

Answers (4)

realMarkusSchmidt
realMarkusSchmidt

Reputation: 4320

I wonder why you would want to do that. Maybe you are sick of misused, excessive URL parameter orgies, and you like the clean RESTful URL style and the elegant way it can be implemented using the new ASP.NET Routing feature.

However, in this case, this is exactly what URL parameters are intended for. It's not bad practice or bad style at all. And there is absolutely no reason to apply SEO witchery to your login page. So why should you make this process less reliable for the user by requiring the session state directly (or indirectly via TempData), or any other workaround?

Upvotes: 4

moi_meme
moi_meme

Reputation: 9318

I would implement a AuthorizationAttribute

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        if (filterContext.Result is HttpUnauthorizedResult)
        {
            filterContext.HttpContext.Session["ReturnUrl"] = filterContext.HttpContext.Request.UrlReferrer.AbsoluteUri
            filterContext.Result = // Your login page controller;
        }

    }
}

This is not tested but might help you find the answer

Good luck to you, please provide your solution when found.

Upvotes: 0

Mike Koder
Mike Koder

Reputation: 1928

Before redirecting to login action store url

TempData["redirect-url"] = "/requested/page/url";

on login action read that value and pass it to login view and put to a hidden field.

Upvotes: 0

Tomasz Jaskuλa
Tomasz Jaskuλa

Reputation: 16013

I would consider to implement my own AuthorizationFilter and do the redirect.

public class AuthorizationFilter : IFilter
{
public bool Perform(ExecuteWhen exec, IEngineContext context,
IController controller, IControllerContext controllerContext)
{
if (context.CurrentUser.IsInRole("Administrator"))
{
return true;
}
context.Response.Redirect("home", "index");
return false;
}
}

Upvotes: 0

Related Questions