WebApi model自动绑定 typeconvert

Controller 


using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using WebApi.Models; namespace WebApi.Controllers { [RoutePrefix("api/demo")] public class DemoController : ApiController { [HttpGet] [Route("action2/{model}")] public Point Action2(Point model) { return model; } } }

自定义Converter

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Web;

namespace WebApi
{
    public class PointTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) //是否可以转换
        {
            return sourceType == typeof(string);
        }
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) //转换成什么类型
        {
            if(value is string)
            {
                return Point.ParsePoint(value as string);
            }
            return base.ConvertFrom(context, culture, value);
        }
    }
}

自定义 Model

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using System.Web.Http.ModelBinding;

namespace WebApi
{
    [TypeConverter(typeof(PointTypeConverter))]
    public class Point
    {
        public double X { get; set; }
        public double Y { get; set; }

        public static Point ParsePoint(string value)
        {
            var split = value.Split(',');
            if (split.Length != 2)
            {
                throw new FormatException("Invalid Point Expression");
            }
            double x;
            double y;
            if(!double.TryParse(split[0],out x)|| !double.TryParse(split[1], out y))
            {
                throw new FormatException("Invalid Point Expression");
            }
            var point = new Point();
            point.X = x;
            point.Y = y;
            return point;
        }
    }
}

  

 

调用的URI

 

http://localhost:20137/api/demo/action2/123,456

 

 

posted @ 2021-10-24 11:59  zq爱生活爱代码  阅读(68)  评论(0编辑  收藏  举报