我正在学习 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/