开发者

How to eliminate ReturnUrl from the browser address

开发者 https://www.devze.com 2022-12-25 15:41 出处:网络
Now on unauthorized attempt to access an action my ASP.NET MVC app redirects user to the login page and generates URL shown below:

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/开发者_JAVA技巧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?


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?


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;
}
}


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.


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.

0

精彩评论

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

关注公众号