MVC action filters using parameters passed to ActionResult?

I created a custom Action Filter with no problem.

But I would like to modify the Action Filter to use some of the parameters actually passed to my method.

So if I have the following method:

[HttpPost]
[MyAttribute]
public ActionResult ViewUserDetails(Guid userId)
{
     // Do something
}

How can I get access to userId from within MyAttribute ? Is there a way I can directly pass it in?

You can try OnActionExecuting override, where you do have access to action parameters.

public class MyAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionParameters.ContainsKey("userId"))
        {
            var userId = filterContext.ActionParameters["userId"] as Guid;
            if (userId != null)
            {
                // Really?! Great!
            }
        }
    }
}

關鍵詞:MVC模式

相關推薦:

asp.net mvc中的用户登錄驗證過濾器

MVC組件分析

利用.Net自帶的票據完成BaseController的未登陸自動跳轉到登陸頁功能

Identity 2.0 User Identity is Null in the Initializer of the MVC 5 Controller

.net mvc 運行監控和錯誤捕捉

ASP.NET MVC 5使用Filter過濾Action參數防止sql注入,讓你代碼安全簡潔

SlickOne 敏捷開發框架介紹(二) -- 多用户/多租户/SAAS軟件基礎框架實現

EntityFrameWork+MVC防SQL注入

Parsing of URL path into action object parameter in ASP.NET MVC

笨鳥先飛之ASP.NET MVC系列之過濾器(03動作過濾器過濾器)