c# - 如何在 Action 过滤器中获取当前模型

标签 c# asp.net-core asp.net-core-mvc

我有一个通用 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/

相关文章:

c# - Azure KeyVault : Azure. Identity.CredentialUnavailableException:DefaultAzureCredential 无法从包含的凭据中检索 token

c# - 如何将 SetBasePath 设置为 Program.Main 上的 dll 位置

c# - 如何将架构过滤器添加到一个 Swashbuckle api 文档版本

c# - (Wix 安装程序)如何包含自定义操作依赖项

c# - 如何从具有组件输出的设备获取高清信号并将其显示在 C# 应用程序的窗口中?

c# - 如何允许 powershell 从 .net 核心 MVC web 应用程序下载 EXE?

c# - 将存储库模式、缓存和 Web 服务链接在一起

.net - 为什么我的 Azure Functions 项目无法识别 Microsoft.AspNetCore.Http 程序集中的类?

c# - 为 ASP.NET Core MVC 显示 404 Not Found 页面

c# - 具有空值的必需字符串属性在 ASP.NET Core 2 Razor 页面中给出 IsValid=true