Dav*_*vid 7 .net c# model-binding asp.net-web-api
鉴于控制器:
public class MyController : ApiController
{
public MyResponse Get([FromUri] MyRequest request)
{
// do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
而型号:
public class MyRequest
{
public Coordinate Point { get; set; }
// other properties
}
public class Coordinate
{
public decimal X { get; set; }
public decimal Y { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
API网址:
/api/my?Point=50.71,4.52
Run Code Online (Sandbox Code Playgroud)
我想在到达控制器之前从查询字符串值转换Point类型的属性.Coordinate50.71,4.52
我在哪里可以加入WebAPI来实现它?
我用模型活页夹做了类似的事情。请参阅本文的选项#3 。
你的模型活页夹将是这样的:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您必须在操作中将其连接到模型绑定系统:
public class MyController : ApiController
{
// GET api/values
public MyRequest Get([FromUri(BinderType=typeof(MyRequestModelBinder))] MyRequest request)
{
return request;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4861 次 |
| 最近记录: |