将以逗号分隔的列表绑定到List< int>.在ASP.NET Web API中 [英] Binding a comma separated list to a List<int> in asp.net web api
问题描述
Web api expecst中的默认活页夹
The default binder in web api expecst
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
.
as I am running out of space in my URL to do a GET
.
我创建了一个课程 公共类CommaSeparatedModelBinder:
I have created a class public class 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);
我已经更改了方法签名以使用模型绑定器
I have altered my method signature to use the model binder like so
public IHttpActionResult Report( [ModelBinder] List<int> PageIds){ // exciting webapi code}
但是我的活页夹中的断点没有被击中(并且列表没有被绑定).
However a break point in my binder is not being hit (and the list does not get bound).
我还需要配置什么?
推荐答案
Make sure to follow all of the steps in this article: Parameter Binding in ASP.NET Web API
您似乎错过了最后一步:
It appears you are missing the last step:
对于模型绑定提供程序,您仍然需要向参数添加[ModelBinder]属性,以告知Web API它应该使用模型绑定程序而不是媒体类型格式化程序.但是现在您无需在属性中指定模型联编程序的类型:
With a model-binding provider, you still need to add the [ModelBinder] attribute to the parameter, to tell Web API that it should use a model binder and not a media-type formatter. But now you don’t need to specify the type of model binder in the attribute:
public HttpResponseMessage Get([ModelBinder] GeoPoint location) { ... }
此外,我从未尝试绑定到List<int>
.您可能无法对绑定模型化,因为它是内置类型.如果是这样,只需将其与自定义类类型一起包装,并确保将[ModelBinder]
属性添加到该类中即可.
Also, I've never tried binding to List<int>
. You may not be able to model bind to it because it is a build-in type. If so, just box it with a custom class type and make sure to add the [ModelBinder]
attribute to the class.
OR ....
更好的解决方案:吻
public IHttpActionResult Report(string PageIds)
{
var ids = PageIds.Split(',');
// exciting web api code and/or more robust checking of the split
}
这篇关于将以逗号分隔的列表绑定到List< int>.在ASP.NET Web API中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!