Asp.net ApiController:如何在请求模型中表示变量参数

问题描述 投票:1回答:2

我正在将旧服务迁移到Asp.net,并且需要保留旧版请求格式。挑战在于POST主体参数的数量是可变的,其数量由count参数指定。例如...

COUNT = 3&PARAM1 = A&PARAM2 = B&参数3 = C

我正在使用ApiController进行另一次调用,它运行良好。但在这种情况下,我不知道如何在不创建一堆占位符属性(PARAM1,PARAM2,...,PARAM100)的情况下定义模型。

所以..如果我有这个..

public class MyController : ApiController
{
  public HttpResponseMessage MyService(MyServiceRequest request)
  {
  }
}

如何定义MyServiceRequest类,以便我可以访问PARAM1,PARAM2等(不仅仅预定义了比我想象的更多的PARAM属性)?

public class MyServiceRequest
{
    public string COUNT { get; set; }

    /* Don't want to have to do this
    public string PARAM1 { get; set; }
    public string PARAM2 { get; set; }
    :
    public string PARAM1000 { get; set; }
    */
}

谢谢!

c# asp.net asp.net-apicontroller
2个回答
2
投票

考虑实施自定义模型绑定

//using System.Web.Http.ModelBinding;
public class LegacyBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        //reading request data
        NameValueCollection formData = actionContext.ControllerContext.Request.Content.ReadAsFormDataAsync().GetAwaiter().GetResult();

        var model = new MyServiceRequest
        {
            Params = new List<string>()
        };
        model.Count = formData["count"];

        foreach (string name in formData)
        {
            //simple check, "param1" "paramRandomsring" will pass
            //if (name.StartsWith("param", StringComparison.InvariantCultureIgnoreCase))
            //more complex check ensures "param{number}" template
            if (Regex.IsMatch(name, @"^param\d+$", RegexOptions.IgnoreCase))
            {
                model.Params.Add(formData[name]);
            }
        }

        bindingContext.Model = model;
        return true;
    }
}

并告诉框架使用此模型绑定器作为具体模型

[ModelBinder(typeof(LegacyBinder))]
public class MyServiceRequest
{
    public string Count { get; set; }

    public List<string> Params { get; set; }
}

阅读docs中有关ASP.NET Web API中模型绑定的更多信息。


0
投票

在这种情况下,我通常使用List param:

public class MyServiceRequest
{
   public List<string> PARAM { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.