C#Web API模型绑定提供程序应该如何工作?

Dan*_*Dan 9 asp.net asp.net-mvc asp.net-web-api asp.net-mvc-5 asp.net-web-api2

我有以下内容:

  • 请求网址:'endpoint/1,2,3?q = foo'
  • 请求绑定的操作:公共对象栏([ModelBinder]列表<T> ids,[FromUri]字符串q)

我想将"1,2,3"片段映射到"ids"参数,因此我根据此链接创建了一个ModelBinderProvider ,它应该调用正确的模型绑定器.

public class MyModelBinderProvider: ModelBinderProvider
{
    public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
    {
        IModelBinder modelBinder = null;

        if (modelType.IsGenericType && (modelType.GetGenericTypeDefinition() == typeof(List<>)))
        {
            modelBinder = new ListModelBinder();   
        }

        return modelBinder;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在Global.asax中注册了提供者,如下所示:

GlobalConfiguration.Configuration.Services.Insert(typeof(ModelBinderProvider), 0, new MyModelBinderProvider());
Run Code Online (Sandbox Code Playgroud)

原因是:我创建了这个提供程序,因为我想要,无论T是什么('1,2,3'或'一,二,三'),绑定工作.

问题是:让'说T'是'int'; 每次发送请求时,'modelType'参数总是'int'而不是我所期望的 - 'List <int>',因此请求没有得到妥善处理.

奇怪的是:做这样的事情有效,但T是专业的,因此不是我想要的:

var simpleProvider = new SimpleModelBinderProvider(typeof(List<int>), new ListModelBinder());
GlobalConfiguration.Configuration.Services.Insert(typeof(ModelBinderProvider), 0, simpleProvider);
Run Code Online (Sandbox Code Playgroud)

我看不出我做错了什么,为什么'modelType'参数不是预期值?

Dou*_*ini 1

这是一个非常古老的问题,但我在这里使用遗留代码遇到了类似的问题。

逗号是保留的,应该避免使用,尽管它们在某些情况下有效,但如果你真的想使用它们......

我认为一旦“1,2,3”是 URL 的路径部分,这更像是一个路由问题,而不是模型绑定器问题。假设我写了一个小的 RouteHandler 来完成这个技巧(请原谅非常简单的“单词到整数”翻译器)。

CsvRouteHandler 从 URL 获取 id 数组,并将其作为整数数组放在 RouteData 上。如果原始数组包含诸如一、二或三之类的单词,则它将每个值转换为 int。

Mvc路由处理程序

protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
{
    var idArrayParameter = requestContext.RouteData.Values["idArray"] != null ? requestContext.RouteData.Values["idArray"].ToString() : null;
    if (string.IsNullOrEmpty(idArrayParameter))
    {
        return base.GetHttpHandler(requestContext);
    }

    requestContext.RouteData.Values.Remove("idArray"); // remove the old array from routedata

    // Note: it is horrible and bugged but and you probably have your own translation method :)
    string[] idArray = idArrayParameter.Split(',');
    int[] ids = new int[idArray.Length];

    for(int i = 0; i < idArray.Length; i++)
    {
        if (!int.TryParse(idArray[i], out ids[i]))
        {
            switch (idArray[i])
            {
                case "one":
                    ids[i] = 1;
                    break;
                case "two":
                    ids[i] = 2;
                    break;
                case "three":
                    ids[i] = 3;
                    break;
            }
        }
    }

    requestContext.RouteData.Values.Add("Id", ids);

    return base.GetHttpHandler(requestContext);

}
}
Run Code Online (Sandbox Code Playgroud)

路由配置:

    routes.Add(
        name: "Id Array Route",
        item: new Route(
            url: "endpoint/{idArray}",
            defaults: new RouteValueDictionary(new { controller = "Test", action = "Index" }),
            routeHandler: new CsvRouteHandler())
    );
Run Code Online (Sandbox Code Playgroud)