C#-如果参数从接口继承,则向控制器参数添加字段值的中间件

C#-如果参数从接口继承,则向控制器参数添加字段值的中间件,c#,asp.net,.net,asp.net-web-api2,middleware,C#,Asp.net,.net,Asp.net Web Api2,Middleware,我需要一些建议或指点。我的中间件知识今天让我失望 假设我有一个如下所示的控制器端点 public int Create([FromBody] InputDto InputDto) public class InputDto : IHasSpecialThingy { public SpecialThingy SpecialThingy { get; set; } // Plus some other cool fields } 这个输入看起来像这样 public int Cr

我需要一些建议或指点。我的中间件知识今天让我失望

假设我有一个如下所示的控制器端点

public int Create([FromBody] InputDto InputDto)
public class InputDto : IHasSpecialThingy
{
    public SpecialThingy SpecialThingy { get; set; }
    // Plus some other cool fields
}
这个输入看起来像这样

public int Create([FromBody] InputDto InputDto)
public class InputDto : IHasSpecialThingy
{
    public SpecialThingy SpecialThingy { get; set; }
    // Plus some other cool fields
}
我试图实现的是一些中间中间件,它检查对象何时从“IHasSpecialThingy”继承,并在其上添加SpecialThingy

我曾尝试创建自己的IModelBinder,但收效甚微

不幸的是,中间件不是我的强项。如有任何建议,将不胜感激

提前感谢您的帮助

编辑


我从一个带有自定义实现的IActionFilter开始。它应该是好的。仍然需要为它找到一些依赖注入。当我把它清理干净后,我会发布一个答案。我仍然会把它打开一段时间,因为有人可能会给我一个更好的解决方案。

我已经找到了解决这个问题的方法。请参阅下面的代码

public class SpecialThingyFilter : IActionFilter
{
    public bool AllowMultiple { get; }

    public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        var commandsWithSpecialThingy = actionContext.ActionArguments
            .Where(x => x.Value != null && x.Value.GetType().GetInterfaces().Contains(typeof(IHasSpecialThingy)))
            .Select(x => x.Value).ToList();

        if (!commandsWithSpecialThingy.Any())
        {
            return await continuation.Invoke();
        }

        foreach (var dto in commandsWithSpecialThingy)
        {
            //Do your magic stuffs here
            ((IHasSpecialThingy)dto).specialThingy = // Something special
        }

        return await continuation.Invoke();
    }
}

如果您有任何问题或遇到类似问题需要帮助,请告诉我。

类型检查不好吗?我认为IModelBinder注册不会检查继承类型,除非我做错了什么。理想情况下,最好有一个通用的解决方案,这样从IHasSpecailThingy继承的任何东西都可以很容易地由该middlewareBtw填充。有人知道如何在自定义IActionFilter而不是ActionFilterAttribute上实现依赖项注入吗?如果您还不知道,请参阅我的答案。