簡體   English   中英

如何在ASP.net MVC 5中限制對控制器操作的訪問

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM