【问题标题】:Web API Model Bind CSV inside complex typeWeb API 模型在复杂类型中绑定 CSV
【发布时间】:2016-11-14 17:03:32
【问题描述】:

我的 ASP.NET Web API 类有一个 GET 端点,它有各种过滤器,这些过滤器从 URI 映射到一个过滤器类:

控制器:

public IHttpActionResult List([FromUri] FilterModel filter)

过滤器类:

public class FilterModel {
    public int Something {get;set;}
    public int[] UserIds {get;set;}
    ...lots of other properties...
}

我希望将 UserIds 作为逗号分隔的列表传递:

http://foo.com/api/things?UserIds=1,2,3

但是,这是 Web API,它期望:

http://foo.com/api/things?UserIds=1&UserIds=2&UserIds=3

有没有简单的方法来解决这个问题。我看到我可以创建一个自定义模型绑定器,但是对于 99% 的模型绑定,我不想更改任何内容。我理想的解决方案是这样的:

public class CustomModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {

        // Access the "default" model that's created from the Uri params
        var model = ???

        // Then do some work to bind the UserIds

        return true;
    }
}

有什么想法吗?

谢谢

【问题讨论】:

  • 您需要创建一个自定义媒体类型格式化程序,例如:link

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


【解决方案1】:

不知道,如果这太简单了,但是作为参数值“1,2,3”只能(afaik)作为字符串传递,您可以使用string.Split转换值(s ) 到 int 数组:

var userIds = Array.ConvertAll(parm.Split(','), int.Parse);

当然,当不是所有的逗号分隔值都是数字时,有可能会遇到 FormatException,因此最好使用多行代码进行转换。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    相关资源
    最近更新 更多