c# - 如何在 ASP.net MVC 5 中限制对 Controller 操作的访问

标签 c# asp.net asp.net-mvc asp.net-mvc-5

我正在学习 ASP.Net MVC 5,我遇到了一个情况,在某些情况下我需要限制对 Controller 操作的访问。假设我的 Controller 中有 5 个 Action ,我想在某些情况下限制其中两个。如何实现这一点我知道我们有内置属性,如 [Authorize]。我可以为 Controller 操作创建用户定义的限制吗?

类似于:

[SomeRule]
public ActionResult Index()
{
   return View();
}

如果我可以创建一个名为“SomeRule”的函数或类,然后在那里添加一些规则。我可以添加一个函数/方法/类,我可以在其中添加一些逻辑并限制访问并在条件下重定向到一般页面不匹配。我是初学者,请指导我。

最佳答案

您想要做的是创建一个自定义操作过滤器,这将允许您在操作中定义自定义逻辑以确定给定用户是否可以/不能访问修饰的操作:

public class SomeRuleAttribute : System.Web.Mvc.ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        // Define some condition to check here
        if (condition)
        {
            // Redirect the user accordingly
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Account" }, { "action", "LogOn" } });
        }
    }
}

如果您需要应用一些值来检查属性的定义位置,您还可以进一步扩展它们并为其设置属性:

public class SomeRule: ActionFilterAttribute
{
    // Any public properties here can be set within the declaration of the filter
    public string YourProperty { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        // Define some condition to check here
        if (condition && YourProperty == "some value")
        {
            // Redirect the user accordingly
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Account" }, { "action", "LogOn" } });
        }
    }
}

这看起来像下面这样:

[SomeRule(YourProperty = "some value")]
public ActionResult YourControllerAction()
{
     // Code omitted for brevity
}

关于c# - 如何在 ASP.net MVC 5 中限制对 Controller 操作的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43746394/

相关文章:

c# - 无法评估表达式,因为代码已优化或 native 框架位于调用堆栈错误消息的顶部

c# - 为什么 caliburn.Micro 解释不起作用?

c# - 尝试首先使用 EF 核心代码时出现 DbUpdateException 错误

c# - 从类文件访问母版页属性

asp.net-mvc - 如何使用表单例份验证来提供保持登录功能?

asp.net-mvc - asp net mvc出现500错误,页面呈现unicode

c# - 大型项目的 Entity Framework

asp.net - 带 CSS 的 Control.ClientID

javascript - JS : "The callee (server [not server application]) is not available and disappeared." accessing window. 开瓶器

asp.net - 下拉列表 asp mvc