ASP.NET MVC HTTPGET操作:数组参数

时间:2015-05-10 18:27:57

标签: asp.net-mvc

如何解决这个案子?

请求:box-decoration-break: clone [纬度] = 123& geoPoints [0] [经度] = 1

我的控制器操作:

[HttpGet]
public HttpResponseMessage Test([FromUri] List<GeoPoint> geoPoints)

请求http://example.com/test?geoPoints[0] .Latitude = 123&amp; geoPoints [0] .Longitude = 1即可,但我需要解决第一种情况。< / p>

请帮忙。

对不起,我的英语不好。

1 个答案:

答案 0 :(得分:1)

您可以像这样创建自定义ModelBinder(仅供参考):

public class GeoPointModelBinder : IModelBinder
{
    public static Regex regex = new Regex(@"^geoPoints\[\(d+)\]\[(longitude|latitude)\]$", RegexOptions.IgnoreCase);

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var query = actionContext.Request.RequestUri.Query;

        var parameters = query
            .Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(it => it.Split('='))
            .Where(it => regex.IsMatch(it[0]))
            .ToDictionary(it => it[0], it => it[1]);

        var points = parameters
            .Select(it => new GeoPoint())
            .ToList();

        foreach (var parameter in parameters)
        {
            var match = regex.Match(parameter.Key);
            var firstGroup = match.Groups[1];
            var secondGroup = match.Groups[2];

            int index = int.Parse(firstGroup.Value);
            string field = secondGroup.Value;

            if (string.Equals(field, "latitude", StringComparison.OrdinalIgnoreCase))
            {
                points[index].Latitude = parameter.Value;
            }
            else
            {
                points[index].Longitude = parameter.Value;
            }
        }

        bindingContext.Model = points;
        return true;
    }
}
...

[HttpGet]
public HttpResponseMessage Test([ModelBinder(typeof(GeoPointModelBinder))]List<GeoPoint> geoPoints) 
{ 
   //... 
}