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模式

相關推薦:

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

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

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

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

EntityFrameWork+MVC防SQL注入

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

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

利用mvc filterconfig屬性實現權限驗證

mvc不登錄的情況下無法跳轉至其他頁面--解決方法之一

10 Points to Secure Your ASP.NET MVC Applications