Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WebAPI:自定义参数映射_C#_.net_Asp.net Web Api_Model Binding - Fatal编程技术网

C# WebAPI:自定义参数映射

C# WebAPI:自定义参数映射,c#,.net,asp.net-web-api,model-binding,C#,.net,Asp.net Web Api,Model Binding,鉴于控制员: public class MyController : ApiController { public MyResponse Get([FromUri] MyRequest request) { // do stuff } } 模型: public class MyRequest { public Coordinate Point { get; set; } // other properties } public clas

鉴于控制员:

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 url:

/api/my?Point=50.71,4.52
我希望在到达控制器之前,将类型
坐标
属性从查询字符串值
50.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;
    }
}
然后必须将其连接到操作中的模型绑定系统:

public class MyController : ApiController
{
    // GET api/values
    public MyRequest Get([FromUri(BinderType=typeof(MyRequestModelBinder))] MyRequest request)
    {
        return request;
    }
}

问题是我必须手动绑定每个属性。假设这个模型还有一个
intradius
属性,我希望它能自动绑定。那可能吗?好的,是的,你必须把所有东西都绑起来。毕竟,您正在告诉系统如何将查询字符串转换为类型的实例。我想你可以添加一些反射hocus pocus来解析其余的,但我在本文中没有这样做。可以只绑定某种类型的属性,更多细节:嗨,David,刚刚看到这个问题,我一直在做类似的工作。要回答您最近的问题,可以只绑定请求中的一些属性而忽略其他属性。在这里的示例中,请求绑定两个u&t参数,但忽略otherData参数。otherData参数仍然正确绑定到请求中的参数,但从自定义模型绑定器中忽略