【问题标题】:Binding a comma separated list to a List<int> in asp.net web api在 asp.net web api 中将逗号分隔的列表绑定到 List<int>
【发布时间】:2015-09-01 16:34:04
【问题描述】:

web api 中的默认绑定器

http://url.com/webapi/Report/?PageIds=3243&PageIds=2365

绑定到

public IHttpActionResult Report(List<int> PageIds){ // exciting webapi code}

我想绑定 http://url.com/webapi/Report/?PageIds=3243,2365

因为我的 URL 空间不足,无法执行 GET

我创建了一个类 公共类 CommaSeparatedModelBinder :

System.Web.Http.ModelBinding.IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
           //Binding in here
        }
     }

并在我的WebApiConfig.cs注册了这个

 var provider = new SimpleModelBinderProvider(
           typeof(List<int>), new CommaSeparatedModelBinder());
            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

我已经更改了我的方法签名以像这样使用模型绑定器

 public IHttpActionResult Report( [ModelBinder] List<int> PageIds){ // exciting webapi code}

但是我的活页夹中的断点没有被击中(并且列表没有被绑定)。

我还需要配置什么?

【问题讨论】:

    标签: c# asp.net-web-api model-binding


    【解决方案1】:

    确保遵循本文中的所有步骤:Parameter Binding in ASP.NET Web API

    您似乎错过了最后一步:

    使用模型绑定提供程序,您仍然需要将 [ModelBinder] 属性添加到参数中,以告诉 Web API 它应该使用模型绑定程序而不是媒体类型格式化程序。但是现在你不需要在属性中指定模型绑定器的类型了:

       public HttpResponseMessage Get([ModelBinder] GeoPoint location) { ... }
    

    另外,我从未尝试绑定到List&lt;int&gt;。您可能无法对它进行模型绑定,因为它是内置类型。如果是这样,只需使用自定义类类型将其装箱,并确保将 [ModelBinder] 属性添加到类中。

    或者....

    更好的解决方案:KISS

    public IHttpActionResult Report(string PageIds)
    {
         var ids = PageIds.Split(',');
         // exciting web api code and/or more robust checking of the split
    }
    

    【讨论】:

    • 不幸的是我没有错过这一步......只是错过了把它放在我的问题中:) 看到编辑!我会尝试我承认我没有想到的盒子和后备!如果可能的话,我更喜欢保持强类型!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多