c# - WebAPI : custom parameter mapping

标签 c# .net asp.net-web-api model-binding

给定 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/

相关文章:

C# LINQ "inner join"集合

c# - 如何让Serilog丰富日志

c# - 基于两点绘制工字梁

c# - 在双手之间移动物体

c# - 将数据从 Excel 文件传输到 MySQL 表

c# - WPF Datagrid 列格式编号以包含逗号

c# - 使用撤消和重做功能绘制形状和字符串

c# - ASP.NET Core 中基于 token 的身份验证

asp.net-web-api - 如何验证 GCP Pub/sub 推送订阅 token ?

c# - CORS 和 ASP.Net Web API