如何确保 action class 参数不为空

How to make sure that a action class parameter is not null

给定以下代码:

public CollectionResult<SetupsDetailsModels> GetSetupsDetails([FromUri]SetupsDetailsCollectionFilterMapping filter)

如果请求不包含任何查询参数,过滤器对象始终为 null,如何确保即使不发送任何参数也始终创建实例?

一个简单的方法是添加一个消息处理程序并添加一个虚拟查询字符串参数,这样总是创建对象,但我真的不喜欢这个解决方案。

谢谢

即使使用动作过滤器,您仍然必须将它添加到您需要它的所有方法中。或者,您可以只使用默认参数。

public CollectionResult<SetupsDetailsModels> GetSetupsDetails([FromUri]SetupsDetailsCollectionFilterMapping filter = new SetupsDetailsCollectionFilterMapping())

考虑一下我在这里找到的想法 Web API Parameter Binding return instance even without request parameters

这就是我要做的:

public override void OnActionExecuting(HttpActionContext actionContext)
{
    var parameterDescriptor = actionContext.ActionDescriptor.GetParameters().FirstOrDefault(x => typeof(CollectionFilterMapping).IsAssignableFrom(x.ParameterType));

    if (parameterDescriptor != null && actionContext.ActionArguments[parameterDescriptor.ParameterName] == null)
    {
        actionContext.ActionArguments[parameterDescriptor.ParameterName] = Activator.CreateInstance(parameterDescriptor.ParameterType);
    }

    base.OnActionExecuting(actionContext);
}

您可以将其设置为路线的默认设置:

            routes.MapRoute(
                name: "test",
                url: "{controller}/{action}/{filter}",
                defaults: new { controller = "Home", action = "Index", filter = new SetupsDetailsCollectionFilterMapping() }
            );

如果 filter 为空,它将创建一个新的 SetupsDetailsCollectionFilterMapping 实例,否则它将是您已经通过的 filter

将节省您必须通过所有方法和添加操作过滤器的麻烦。

刚刚用类似的东西对其进行了测试并且有效。