给定 Controller :
public class MyController : ApiController
{
public MyResponse Get([FromUri] MyRequest request)
{
// do stuff
}
}
和模型:
public class MyRequest
{
public Coordinate Point { get; set; }
// other properties
}
public class Coordinate
{
public decimal X { get; set; }
public decimal Y { get; set; }
}
API 网址:
/api/my?Point=50.71,4.52
我希望在到达 Controller 之前从查询字符串值 50.71,4.52
转换 Coordinate
类型的 Point
属性。
我在哪里可以连接到 WebAPI 来实现它?
最佳答案
我用模型 Binder 做了类似的事情。 请参阅 this article 的选项 #3 .
您的模型 Binder 将是这样的:
public class MyRequestModelBinder : IModelBinder {
public bool BindModel(HttpActionContext actionContext,
ModelBindingContext bindingContext) {
var key = "Point";
var val = bindingContext.ValueProvider.GetValue(key);
if (val != null) {
var s = val.AttemptedValue as string;
if (s != null) {
var points = s.Split(',');
bindingContext.Model = new Models.MyRequest {
Point = new Models.Coordinate {
X = Convert.ToDecimal(points[0],
CultureInfo.InvariantCulture),
Y = Convert.ToDecimal(points[1],
CultureInfo.InvariantCulture)
}
};
return true;
}
}
return false;
}
}
然后您必须将其连接到操作中的模型绑定(bind)系统:
public class MyController : ApiController
{
// GET api/values
public MyRequest Get([FromUri(BinderType=typeof(MyRequestModelBinder))] MyRequest request)
{
return request;
}
}
关于c# - WebAPI : custom parameter mapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18191213/