C# 多类型webapi参数绑定

C# 多类型webapi参数绑定,c#,asp.net-web-api,webapi,C#,Asp.net Web Api,Webapi,是否可能有一个api端点,其方法的符号可以接受可以是单个对象或对象集合的参数 我有这样一种方法: [HttpPost, Route("DoSomething")] public async Task<IHttpActionResult> DoSomething([FromBody] MyType xxx, CancellationToken cancel) [HttpPost,路线(“DoSomething”)] 公共异步任务DoSomething([FromB

是否可能有一个api端点,其方法的符号可以接受可以是单个对象或对象集合的参数

我有这样一种方法:

[HttpPost, Route("DoSomething")]
public async Task<IHttpActionResult> DoSomething([FromBody] MyType xxx, CancellationToken cancel)
[HttpPost,路线(“DoSomething”)]
公共异步任务DoSomething([FromBody]MyType xxx,CancellationToken cancel)
我需要修改此方法以接受MyType类的集合(数组、可枚举、列表……无所谓)

[HttpPost,路线(“DoSomething”)]
公共异步任务DoSomething([FromBody]IEnumerable xxx,CancellationToken cancel)
无论如何,在一段时间内,调用此端点的客户端将继续向我发送单个对象
{}
,而不是对象的集合
[{},{}]

是否可以修改此端点以接受这两种类型?

我认为有两种解决方案:

  • 将数据设置为
    字符串
    ,您可以自己以任何方式对其进行解析,您可以处理字符串,为其提供不同的规则以判断应转换的类型,例如,如果包含
    [/code>,则将其解析为列表,否则为单个对象

  • 编写两种方法一种接受列出另一种Obj,并在api文档中清楚地写下用法,然后将文档提供给用户


  • 您可以使用自定义的
    JsonConverter
    执行此操作。例如,这应该可以工作,或者至少足以让您自定义:

    public class SingleOrListConverter<T> : JsonConverter
    {
        public override bool CanConvert(Type objectType) => objectType == typeof(List<T>);
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, 
            JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);
    
            if (token.Type == JTokenType.Array)
            {
                return token.ToObject<List<T>>();
            }
    
            return new List<T>
            {
                token.ToObject<T>()
            };
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    
    现在只需使用一个端点:

    public async Task<IHttpActionResult> DoSomething(
        [FromBody] IEnumerable<MyType> xxx, CancellationToken cancel)
    
    公共异步任务DoSomething(
    [FromBody]IEnumerable xxx,CancellationToken取消)
    
    这是.NET Framework还是.NET Core?换句话说,它使用的是JSON.NET还是System.Text.JSON?@DavidG.NET full Framework Newtonsoft.JSON编写两个类似于我上面所写的方法时,我会收到此错误“404错误请求”消息:“发现多个操作与请求匹配”'尝试为该方法指定不同的名称,以便url路由不同
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters
        .Add(new SingleOrListConverter<string>());
    
    public async Task<IHttpActionResult> DoSomething(
        [FromBody] IEnumerable<MyType> xxx, CancellationToken cancel)