簡體   English   中英

如何將參數從動作過濾器傳遞到控制器方法

[英]How to pass a parameter from action filter to a controller method

我想做一個自定義的認證過濾器。 如果一切成功,它將返回用戶。 但是,在控制器中,我再次需要它來查找用戶,但這在數據庫中再次搜索他的效率很低。 我想重用在ActionFilter獲得的信息。 這是偽代碼,確切顯示了我要實現的目標:

public class AuthenticateAttribute : ActionFilterAttribute
{
    public async override void OnActionExecuting(ActionExecutingContext context)
    {
        // some code here...
        var user = // some code...

        if (user == null)
        {
            // error, not authenticated
        }

        // yes! authentication succeeded! now we have found the user, it would be clever to pass
        // it to the controller method so that it does not have to look it up once again in the database
        parameters.Add("userFound", user);
    }
}

有沒有辦法做到這一點? 我想無論如何都可以通過controller方法訪問它。 例如這樣:

parameters["userFound"]

謝謝!

ActionExecutingContext您具有對控制器和請求的完全訪問權限,然后您可以在許多地方放置參數,這里僅ActionExecutingContext幾個:

  • context.Controller.ViewBag ,它也可以在您的視圖中訪問。
  • context.Controller.ViewData,也可以在您的視圖中訪問它。
  • context.HttpContext.Session ,如果您正在使用會話。

請記住, ActionExecutingContextControllerContext派生的,並且ControllerContext可以在控制器中的任何位置訪問。

但是我會避免這種情況,因為(至少對我而言)這有點奇怪。 您的控制器將根據該參數執行不同的操作(與對User.IsAuthenticated的檢查沒有太大不同),然后我真正要做的是在操作過濾器中重定向到一個不同的操作方法:

if (user == null) // not authenticated
{
    var data = context.HttpContext.Request.RequestContext.RouteData;
    var currentAction = data.GetRequiredString("action");
    var currentController = data.GetRequiredString("controller");

    context.Result = new RedirectToRouteResult(
        new RouteValueDictionary 
        { 
            { "controller", currentController }, 
            { "action", currentAction + "_NotAuthenticated" } 
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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