如何在动作过滤器中获取当前模型 [英] How to get current model in action filter

查看:142
本文介绍了如何在动作过滤器中获取当前模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的动作过滤器,我想在OnActionExecuting方法中获取当前模型.我当前的实现如下:

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

public class CommandFilter<T> : IActionFilter where T : class, new()
{
    public void OnActionExecuting(ActionExecutingContext actionContext)
    {
        var model= (T)actionContext.ActionArguments["model"];
    }
}

如果我的所有型号名称都相同,则效果很好.但是我想使用differnet模型名称.

It works well if my all model names are same. But i want to use differnet model names.

如何解决这个问题?

修改

public class HomeController : Controller
{
    [ServiceFilter(typeof(CommandActionFilter<CreateInput>))]
    public IActionResult Create([FromBody]CreateInput model)
    {
        return new OkResult();
    }
}

推荐答案

ActionExecutingContext.ActionArguments只是一个字典,

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; }

如果需要避免使用硬编码的参数名称(模型"),则需要遍历它.来自针对asp.net的相同的答案:

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
    }
}

这篇关于如何在动作过滤器中获取当前模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆