Generate a return Url with a custom AuthorizeAttribute

泪湿孤枕 提交于 2019-11-30 22:14:13
EvilDr

Finally figured it out, although somebody might be able to suggest a better way...

filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Login",
                                action = "Login",
                                returnUrl = filterContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped)
                            }));

This was just what I needed for the same problem although looked slightly different:

filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary
                {
                    { "controller", "Account" },
                    { "action", "Login" },
                    { "returnUrl", filterContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped) }
                });

Thanks!

there are many way to implement this. you should use filterContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped) for getting returnUrl.

first way:

 var returnUrl = filterContext.HttpContext.Request.Url?.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped) ?? "";
 if (!string.IsNullOrWhiteSpace(returnUrl))
 {
       returnUrl = "/" + returnUrl;
 }

 filterContext.Result = new RedirectResult($"~/Login/Login{returnUrl}");

second way:

filterContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary(
        new
        {
              controller = "Login",
              action = "Login",
              area = "",
              returnUrl = filterContext.HttpContext.Request.Url?.GetComponents(UriComponents.PathAndQuery,
                            UriFormat.SafeUnescaped)
         }));

just , dont forget set Area.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!