你想要做的是創建一個自定義操作過濾器,這將允許您在操作中定義自定義邏輯來確定給定用戶可以/無法訪問的裝飾作用:
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
}
檢查有關asp.net的MVC過濾器。 – Christos
@Christos:你能看到我的編輯,請 – Unbreakable
不能你剛剛添加的路由選擇忽略這個控制器的任何請求或重定向到任何其他 –