如何在动作filter中获取当前模型

我有一个通用的动作filter,我想在OnActionExecuting方法中获取当前模型。 我目前的实现如下:

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

如果我的所有型号名称相同,它的效果很好。 但我想使用不同的模型名称。

如何解决这个问题呢?

编辑

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

ActionExecutingContext.ActionArguments只是一个字典,

  ///  /// Gets the arguments to pass when invoking the action. Keys are parameter names. ///  public virtual IDictionary ActionArguments { get; } 

如果您需要避免使用硬编码的参数名称(“模型”),则需要循环访问它。 来自asp.net 的相同SO答案 :

当我们创建一个通用的动作filter,需要处理一类类似的对象以满足某些特定的需求时,我们可以让我们的模型实现一个接口=>知道哪个参数是我们需要处理的模型,我们可以调用这些方法界面。

在你的情况下,你可能写这样的东西:

 public void OnActionExecuting(ActionExecutingContext actionContext) { foreach(var argument in actionContext.ActionArguments.Values.Where(v => v is T)) { T model = argument as T; // your logic } } 

您可以使用ActionExecutingContext.Controller属性

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

并将结果转换为基础MVC Controller可以访问模型:

 ((Controller)actionExecutingContext.Controller).ViewData.Model 

如果您的控制器操作有多个参数,并且在您的filter中您想要选择通过[FromBody]绑定的[FromBody] ,那么您可以使用reflection执行以下操作:

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