如何在ASP.net MVC 5中限制控制器操作的访问

3

我正在学习ASP.Net MVC 5,并遇到一个需要在某些情况下限制访问控制器操作的案例。 假设我的控制器中有5个操作,我想在某些情况下限制其中两个操作。 我知道我们有内置属性如[Authorize],但我能否创建用户定义的限制以控制器操作为基础。

类似于:

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

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


检查一下ASP.NET MVC中的过滤器。 - Christos
@Christos:请问您能看到我的编辑吗? - Unbreakable
你能否在这个控制器中添加路由选项来忽略任何请求或将其重定向到其他页面? - Mostafa Mohamed Ahmed
@Christos:我的错,它按预期工作。 - Unbreakable
1个回答

6

您需要创建一个自定义的Action Filter,它允许您在操作中定义自定义逻辑来确定给定用户是否能够访问/无法访问已装饰的操作:

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
}

如果我选择第一种方法,我的操作方法应该是什么样子? - Unbreakable
1
我是一个初学者,请原谅我的无知。 - Unbreakable
好的,我采用了第一种方法,并在一个操作方法上使用了[SomeRuleAttribute]进行装饰。但是即使该控制器动作尚未被调用,这个SomeRuleAttribute也会被触发。 - Unbreakable
我只在一个操作上使用了[SomeRuleAttribute]装饰器。但即使该操作没有被调用,该类仍然会受到影响。请指导我。 - Unbreakable

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接