我正在将旧服务迁移到Asp.net,并且需要保留旧的请求格式。挑战在于POST正文参数的数量是可变的,而数量由count参数指定。例如...
COUNT = 3&PARAM1 = A&PARAM2 = B&PARAM3 = 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; }
*/
}
谢谢!
答案 0 :(得分: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中的模型绑定的更多信息。
答案 1 :(得分:0)
在这种情况下,我通常使用 (9)
(4 170)
(1 6) (null null)
(null null)(null null)(null null)(30 null) <-- no way to reach node 30
参数:
def nameOfBestCustomer(sales, customers) :
#@param: sales and customers lists
#@return: none
bestCustomers = []
salesMax = 0
salesMax = max(sales)
for i, sale in enumerate(sales):
if sale == salesMax:
bestCustomers.append(customers[i])
print("The best customer of the day was", end='')
for customer in bestCustomers:
print(' ' + customer, end='')
print('.')