c# - 限制对 MVC 操作的访问

标签 c# asp.net-mvc

我有一个 ASP.NET MVC 网站,我在其中建立了一个权限系统。例如,当当前用户没有足够的权限时,有些链接会被隐藏。但是,如果他们手动输入该链接的 URL,他们仍然可以访问内容。

我知道我可以使用 [Authorize] 属性来阻止没有正确用户角色的用户,但是我如何实现我自己的属性来阻止不符合自定义要求的用户的操作,无需在每个操作中编写手动检查?

最佳答案

您可以编写自定义 Authorize 属性并覆盖 AuthorizeCore 方法,您可以在其中放置自定义授权逻辑:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authroized = base.AuthorizeCore(httpContext);
        if (!authroized)
        {
            return false;
        }

        // at this stage the base authorization process has passed.
        // now implement your custom authorization logic and return true or false

        // here you have access to the HttpContext and as a consequence to all
        // request and route parameters so you could implement any 
        // authorization logic you want

        // And of course if you want a completely custom authorization logic 
        // ignoring the base functionality don't call the base method above
        // but completely override anything here
    }
}

现在剩下的就是用这个自定义属性装饰相应的 Controller / Action 。

关于c# - 限制对 MVC 操作的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11091235/

相关文章:

c# - Xamarin 设置 EntryCell 的绑定(bind)

c# - Unity 测试工具使用 GameObject 进行单元测试给出 "You are trying to create a MonoBehaviour using the ' new' 关键字。这是不允许的。”

c# - 重载 '+' 的不可变列表是否有意义?

asp.net-mvc - SignalR 客户端 - 远程服务器返回错误(401 未经授权)

c# - ASP.NET MVC 在授权后保留发布数据

asp.net - 如何在 ASP.NET MVC 中将 url 路径转换为完整或绝对 url?

jquery - jquery 重定向后在 asp.net mvc 中查找引用页面

c# - 为什么禁用的按钮可以点击?

asp.net-mvc - Visual Studio 在 razor 语句中显示语法错误但有效

c# - 我想要一个关于循环命名空间依赖的警告