微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

需要像这样实例化具有默认参数的空模型

如何解决需要像这样实例化具有默认参数的空模型

我有以下使用 .NET 4.6 的 asp.net WebApi2 路由,说明了我遇到的问题:

[Route("books/{id}")]
[HttpGet]
public JsonResponse GetBooks(string id,[FromUri]DescriptorModel model)

使用以下模型:

public class DescriptorModel
{
    public bool Fiction { get; set; } = false;

    // other properties with default arguments here
}

我试图允许将 Fiction 属性设置为认值(如果在获取请求期间未指定)。

当我明确指定 Fiction 属性时,它可以正常工作:

curl -X GET --header 'Accept: application/json' 'http://127.0.0.1:11000/api/v1/books/516.375/?Fiction=false'

但是,在进行以下测试时(省略带有认参数的属性):

curl -X GET --header 'Accept: application/json' 'http://127.0.0.1:11000/api/v1/books/516.375'

“model”的值绑定为 null,这不是我要找的。我的问题是如何简单地允许在模型绑定过程中/之后但在调用控制器的“GetBooks”操作方法之前实例化使用认值定义的模型。

注意。我使用带有 GET 请求的模型的原因是,在 swagger 中记录要容易得多,因为这样我的 GET/POST 操作可以在许多情况下通过继承重用相同的模型。

解决方法

由于您使用 id 作为 FromUri,因此您可以将模型与 get 一起使用的唯一方法是将 url 与查询字符串一起使用

[Route("~/GetBooks/{id?}")]
[HttpGet]
public IActionResult GetBooks(string id,[FromQuery] DescriptorModel model)

在这种情况下,您的网址应该是

'http://127.0.0.1:11000/api/v1/books/?Name=name&&fiction=true'

//or if fiction==false just
'http://127.0.0.1:11000/api/v1/books/?Name=name'

//or if want to use id
'http://127.0.0.1:11000/api/v1/books/123/?Name=name&&fiction=true'

以您的方式使用模型仅适用于 [FromForm] 或 [FromBody]。 要将其用作 MVC 推荐,请尝试此

[Route("books/{id}/{param1}/{param2}/{fiction?}")]
[HttpGet]
public JsonResponse GetBooks(string id,string param1,string param2,bool fiction)

顺便说一句,您不需要将 bool 设为默认值,因为它在任何情况下都是 false

如果您想使用 uri 中的 ID 和 DescriptorModel,则只有将 Id 添加到 DescriptorModel 才能执行此操作

[Route("books/{id}/{param1}/{param2}/{fiction?}")]
[HttpGet]
public JsonResponse GetBooks(DescriptorModel model)

更新

如果您的 mvc 不支持 [FromQuery],您可以在这样的操作中使用 RequestQuery


 var value= context.Request.Query["value"];

但最好更新到 MVC 6。

,

我无法弄清楚如何通过模型绑定来做到这一点,但我能够使用操作过滤器来完成同样的事情。

这是我使用的代码(注意它每个动作只支持一个空模型,但如果需要,这可以很容易地修复):

public class NullModelActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        object value = null;
        string modelName = string.Empty;

        // are there any null models?
        if (context.ActionArguments.ContainsValue(null))
        {
            // Yes => iterate over all arguments to find them.
            foreach (var arg in context.ActionArguments)
            {
                // Is the argument null?
                if (arg.Value == null)
                {
                    // Search the parameter bindings to find the matching argument....
                    foreach (var parameter in context.ActionDescriptor.ActionBinding.ParameterBindings)
                    {
                        //  Did we find a match?
                        if (parameter.Descriptor.ParameterName == arg.Key)
                        {
                            // Yes => Does the type have the 'Default' attribute?
                            var type = parameter.Descriptor.ParameterType;
                            if (type.GetCustomAttributes(typeof(DefaultAttribute),false).Length > 0)
                            {
                                // Yes => need to instantiate it
                                modelName = arg.Key;
                                var constructor = parameter.Descriptor.ParameterType.GetConstructor(new Type[0]);
                                value = constructor.Invoke(null);

                                // update the model state
                                context.ModelState.Add(arg.Key,new ModelState { Value = new ValueProviderResult(value,value.ToString(),CultureInfo.InvariantCulture) });
                            }
                        }
                    }
                }
            }

            // update the action arguments
            context.ActionArguments[modelName] = value;
        }
    }
}

我像这样创建了一个 DefaultAttribute 类:

[AttributeUsage(AttributeTargets.Class,AllowMultiple = false)]
public class DefaultAttribute : Attribute
{
}

然后我将该属性添加到我的描述符类中:

[Default]
public class DescriptorModel
{
    public bool Fiction { get; set; } = false;

    // other properties with default arguments here
}

最后在

中注册了动作过滤器
public void Configure(IAppBuilder appBuilder)
{
    var config = new HttpConfiguration();
    // lots of configuration here omitted
    config.Filters.Add(new NullModelActionFilter());
    appBuilder.UseWebApi(config);
}

我绝对认为这是一个黑客(我认为我真的应该通过模型绑定来做到这一点)但它完成了我需要做的事情,我被赋予了 ASP.NET(不是 Core)/WebApi2/.NET 的约束框架,所以希望其他人能从中受益。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。