views:

254

answers:

4

Hi, guys. 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?

A: 

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;
}
}
Thomas Jaskula
A: 

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.

Mika Kolari
but redirect is done automatically by the MVC infrastructure. All I do is set [Authorize] attribute on my action
Alexander Efimov
A: 

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.

moi_meme
+4  A: 

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?

markus