zoukankan      html  css  js  c++  java
  • Asp.net Web Api 数据绑定

    1、假设有如下api,传入经纬度获取城市信息,api可以定义为api/geodata?latitude=47.678558&Longitude=-122.130989 下面我来尝试将经纬度信息作为一个参数进行提交。

    api/geodata?location=47.678558,-122.130989

    首先,我们肯定想到可以在api中获取location再去对location进行解析,这种方法不推荐,下面我们尝试另外一种方法直接变量接收。

    [TypeConverter(typeof(GeoPointConverter))]//标记类型转换器
        public class GeoPoint
        {
            public double Latitude { get; set; }
            public double Longitude { get; set; }
    
            public static bool TryParse(string s, out GeoPoint result)
            {
                result = null;
    
                var parts = s.Split(',');
                if (parts.Length != 2)
                {
                    return false;
                }
    
                double latitude, longitude;
                if (double.TryParse(parts[0], out latitude) &&
                    double.TryParse(parts[1], out longitude))
                {
                    result = new GeoPoint() { Longitude = longitude, Latitude = latitude };
                    return true;
                }
                return false;
            }
        }
    
        //类型转换器
        class GeoPointConverter : TypeConverter
        {
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            {//检查是否能够转换
                if (sourceType == typeof(string))
                {
                    return true;
                }
                return base.CanConvertFrom(context, sourceType);
            }
    
            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
            {//进行数据类型转换
                if (value is string)
                {
                    GeoPoint point;
                    if (GeoPoint.TryParse((string)value, out point))
                    {
                        return point;
                    }
                }
                return base.ConvertFrom(context, culture, value);
            }
        }

    以上包括一个实体类和一个类型转换类,由类型转换类负责把string类型的数据转化成GeoPoint。

    Action定义如下:

            [Route("geodata")]
            public IHttpActionResult GetGeoData(GeoPoint geoPoint)
            {
                return Ok(geoPoint);
            }
  • 相关阅读:
    cloud-api-service和cloud-iopm-web提交merge方法
    Java知识点-判断null、空字符串和空格
    Windows本机搭建Redis
    api-gateway-engine知识点(2)
    能够提高开发效率的Eclipse实用操作
    IOP知识点(2)
    获取分辨率及dp/px换算
    Android软件自动更新(自定义处理,不使用第三方)
    友盟自动更新参数详解
    [Android]ping -c 1 -w 100 sina.cn的解析
  • 原文地址:https://www.cnblogs.com/CanFly/p/4312831.html
Copyright © 2011-2022 走看看