asp.net – 使用自定义AuthorizeAttribute生成返回Url

我有自定义授权属性

using System;
using System.Web.Mvc;
using System.Web.Routing;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,Inherited = true,AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login",action = "Login" }));
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

…我用来装饰某些控制器:

[MyAuthorizeAttribute(Roles = "Superman,Batman,Spiderman")]
public class SuperHeroController : Controller
{
    // ....
}

任何人都可以解释如何修改授权代码,以便如果授权失败,登录URL包括ReturnUrl(当前控制器/方法的URL)?

这基本上是试图模仿Web表单ReturnUrl逻辑,但是以一种聪明的方式,我不必手动使用字符串作为URL.

解决方法

终于想通了,虽然有人可能会建议一个更好的方法……

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....