[英]How to provide access of action methods for particular user in a controller in asp.net mvc
[英]How to restrict access of controller action in ASP.net MVC 5
我正在学习ASP.Net MVC 5,我遇到了一些需要在某些情况下限制对控制器操作的访问的情况。 假设我的控制器中有5个动作,我想在某些情况下限制其中的两个。如何实现这一点我知道我们有内置的属性,如[Authorize]
。 我可以为控制器操作创建用户定义的限制。
就像是:
[SomeRule]
public ActionResult Index()
{
return View();
}
如果我可以创建一个名为“SomeRule”的函数或类,然后在那里添加一些规则。我可以添加一个函数/方法/类,我可以添加一些逻辑并限制访问并在条件不匹配时重定向到genreal页面。 我是初学者请指导我。
您要做的是创建一个自定义动作过滤器,它允许您在动作中定义自定义逻辑,以确定给定用户是否能够/无法访问已修饰的动作:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.