![](/img/trans.png)
[英]How to pass a method or parameter to an action filter in ASP.Net MVC
[英]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.HttpContext.Session
,如果您正在使用會話。 請記住, ActionExecutingContext
從ControllerContext
派生的,並且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.