How to get current model in action filter

前端 未结 3 1379
粉色の甜心
粉色の甜心 2020-12-17 10:25

I have a generic action filter, and i want to get current model in the OnActionExecuting method. My current implementation is like below:

public         


        
相关标签:
3条回答
  • 2020-12-17 10:51

    ActionExecutingContext.ActionArguments is just a dictionary,

        /// <summary>
        /// Gets the arguments to pass when invoking the action. Keys are parameter names.
        /// </summary>
        public virtual IDictionary<string, object> ActionArguments { get; }
    

    And you need to loop through it if you need to avoid hardcoded parameter name ("model"). From the same SO answer for asp.net:

    When we create a generic action filter that needs to work on a class of similar objects for some specific requirements, we could have our models implement an interface => know which argument is the model we need to work on and we can call the methods though the interface.

    In your case you may write something like this:

    public void OnActionExecuting(ActionExecutingContext actionContext)
    {
        foreach(var argument in actionContext.ActionArguments.Values.Where(v => v is T))
        {
             T model = argument as T;
             // your logic
        }
    }
    
    0 讨论(0)
  • 2020-12-17 10:51

    You can use ActionExecutingContext.Controller property

        /// <summary>
        /// Gets the controller instance containing the action.
        /// </summary>
        public virtual object Controller { get; }
    

    and converting result to base MVC Controller get access to model:

    ((Controller)actionExecutingContext.Controller).ViewData.Model
    
    0 讨论(0)
  • 2020-12-17 11:03

    In case your controller action has multiple arguments and in your filter you want to select the one that is bound via [FromBody], then you can use reflection to do the following:

    public void OnActionExecuting(ActionExecutingContext context)
    {
        foreach (ControllerParameterDescriptor param in context.ActionDescriptor.Parameters) {
            if (param.ParameterInfo.CustomAttributes.Any(
                attr => attr.AttributeType == typeof(FromBodyAttribute))
            ) {             
                var entity = context.ActionArguments[param.Name];
    
                // do something with your entity...
    
    0 讨论(0)
提交回复
热议问题