7

给定控制器:

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

我希望在到达控制器之前从查询字符串值转换Point类型的属性。Coordinate50.71,4.52

我在哪里可以连接到 WebAPI 来实现它?

4

1 回答 1

3

我用模型活页夹做了类似的事情。请参阅本文的选项#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;
    }
}

然后,您必须将其连接到操作中的模型绑定系统:

public class MyController : ApiController
{
    // GET api/values
    public MyRequest Get([FromUri(BinderType=typeof(MyRequestModelBinder))] MyRequest request)
    {
        return request;
    }
}
于 2013-08-12T17:12:39.647 回答