c# - 将非 MVC 相关属性应用于 MVC 操作

标签 c# .net asp.net-mvc security cross-cutting-concerns

我们的应用程序具有 PermissionAttribute 的概念。此属性在我们应用程序的基础层中定义,我们的命令和查询使用该属性进行修饰。由于此属性是在基础层中定义的,我们不能(也不想)让它继承自 FilterAttribute 或实现 System.Web.Mvc.IActionFilter

我们仍然希望将此属性应用于 Controller 操作,如下所示:

[Permission(Permissions.Administration.ManageUsers)]
public ActionResult Index()
{
    return this.View();
}

应根据此属性应用适当的安全检查。我一直在浏览 MVC 代码库,以找到合适的 Hook 来自定义 MVC 行为,以允许基于此自定义属性添加这些安全检查。我想创建一个自定义 ControllerActionInvoker,它从其 GetControllerDescriptor 方法返回一个自定义 ReflectedControllerDescriptor,这将返回 FilterAttribute将根据 PermissionAttribute 的存在创建,但感觉工作量很大,我不确定这是正确的路径。

自定义 MVC 管道以便我们可以处理这种非 MVC 相关属性的有效且愉快的方法是什么?

最佳答案

我会这样做。首先像这样创建您自己的 AuthorizeAttribtues 实现:

public class PermissionAuthoriseAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //Leaving the implementation of this to you, but you check if your
        //PermissionAttribute is assigned and call it's methods.
        if(...)
            return true;

        //You may want to check this first, depending on your requirements
        return base.AuthorizeCore(httpContext);
    }
}

然后通过将此行添加到 FilterConfig.cs 文件,将其应用到您的项目中:

filters.Add(new PermissionAuthoriseAttribute());

关于c# - 将非 MVC 相关属性应用于 MVC 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25887708/

相关文章:

c# - 从 richtextbox 保存格式化文本

c# - 如何从 C# UNity 中写入的 JSON 格式的文件中删除特殊字符或不需要的符号?

c# - C#有关线程安全的问题

c# - 我什么时候应该在 IEnumerable<T> 的上下文中使用 .Count() 和 .Count

c# - "ReferenceEquals(myObject, null)"比 "myObject == null"更好吗?

c# - 在 .NET CF 中预处理和搜索文本文件的最佳方式

c# - 参数是线程安全的吗?

javascript - Kendo MVC 网格过滤器自定义不起作用

c# - 属性的客户端 ID (ASP.Net MVC)

asp.net-mvc - 强制使用 HTTP 而不是 HTTPS