我有一个通用 Action 过滤器,我想在 OnActionExecuting
方法中获取当前模型。我当前的实现如下所示:
public class CommandFilter<T> : IActionFilter where T : class, new()
{
public void OnActionExecuting(ActionExecutingContext actionContext)
{
var model= (T)actionContext.ActionArguments["model"];
}
}
如果我的所有型号名称都相同,效果会很好。但我想使用不同的型号名称。
如何解决这个问题?
编辑
public class HomeController : Controller
{
[ServiceFilter(typeof(CommandActionFilter<CreateInput>))]
public IActionResult Create([FromBody]CreateInput model)
{
return new OkResult();
}
}
最佳答案
ActionExecutingContext.ActionArguments 只是一个字典,
/// <summary>
/// Gets the arguments to pass when invoking the action. Keys are parameter names.
/// </summary>
public virtual IDictionary<string, object> ActionArguments { get; }
如果您需要避免硬编码参数名称(“模型”),则需要遍历它。来自 the same SO answer对于 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.
在你的情况下你可以这样写:
public void OnActionExecuting(ActionExecutingContext actionContext)
{
foreach(var argument in actionContext.ActionArguments.Values.Where(v => v is T))
{
T model = argument as T;
// your logic
}
}
关于c# - 如何在 Action 过滤器中获取当前模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38895830/