考虑以下 ApiController:
public class SomeController : ApiController
{
[HttpGet]
public class SomeFunction(int someVal = 0) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
这按预期工作:
http://myserver/myApp/Some/SomeFunction?someVal=0
Run Code Online (Sandbox Code Playgroud)
但是当它被调用时我遇到了这个函数的问题
http://myserver/myApp/Some/SomeFunction?someVal=0&someVal=0
Run Code Online (Sandbox Code Playgroud)
现在我试图了解当时和那里发生的事情。我没有收到错误消息,但函数的输出与预期不同。
Web API 参数绑定无法将查询字符串中的多个参数转换为数组,因此您必须有两个选择:
第二个选项包括获取查询字符串名称-值对,并自己解析它们。要获取名称值对,请使用以下命令:
Request.GetQueryNameValuePairs()
Run Code Online (Sandbox Code Playgroud)
要提取 int 值,您可以执行以下操作:
var values= Request.GetQueryNameValuePairs()
.Where(kvp => kvp.Key == "someVal")
.Select(kvp => int.Parse(kvp.Value))
.ToArray();
Run Code Online (Sandbox Code Playgroud)
当然,您应该控制解析等方面的错误。这是一个基本的示例代码。
这是第一个选项的模型绑定器的实现:
public class IntsModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof (Ints))
{
return false;
}
var intValues = actionContext.Request.GetQueryNameValuePairs()
.Where(kvp => kvp.Key == bindingContext.ModelName)
.Select(kvp => int.Parse(kvp.Value))
.ToList();
bindingContext.Model = new Ints {Values = intValues};
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
同样,这是一个基本的实现,除此之外,它缺乏对错误的控制。
这是在操作中使用它的一种方法,但是,请阅读参数绑定的链接以查看其他(更好的)使用它的方法:
// GET api/Test?keys=1&keys=7
public string Get([ModelBinder(typeof(IntsModelBinder))]Ints keys)
{
return string.Format("Keys: {0}", string.Join(", ", keys.Values));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3681 次 |
| 最近记录: |