了解 ASP.NET MVC 生命周期:为什么模型在 ActionFilter 中不可用?

Understanding ASP.NET MVC Lifecycle: Why is Model not available in ActionFilter?

我创建了以下自定义 ActionFilter,当我尝试访问以下代码中的 Model 时,它为空:

public class CustomPermissionCheckAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        OrganisationBaseController orgBaseController = context.Controller as Controller;
        var vm = ((Controller)context.Controller).ViewData.Model as MyViewModel; // null

        // check if current user has permission to vm.OrganisationId

        base.OnActionExecuting(context);
    }
}

我想了解为什么 Model 为空?根据ASP.NET MVC Lifecycle,ActionFilters是在Model Binder之后执行的,所以我不确定为什么Model不可用?


这就是我注册上述动作过滤器的方式:

[HttpPost]
[CustomPermissionCheck]
public ActionResult UpdateBranch(MyViewModel myViewModel)
{
    if (ModelState.IsValid)
    {
        // so something 
    }
    return View();
}

可以试试这个来访问请求模型:

MyViewModel vm = context.ActionParameters.Values.OfType<MyViewModel>().SingleOrDefault();