Skip to content

Instantly share code, notes, and snippets.

@karbyninc
Last active February 11, 2016 15:21
Show Gist options
  • Save karbyninc/510868b547df4ddd0c69 to your computer and use it in GitHub Desktop.
Save karbyninc/510868b547df4ddd0c69 to your computer and use it in GitHub Desktop.
Using TypeConverters in Web API
public class Color
{
public double Red { get; set; }
public double Green { get; set; }
public double Blue { get; set; }
public Color()
{ }
}
public class ColorController : ApiController
{
public IHttpActionResult Get(double red, double green, double blue)
{
return Ok(new Color { Red = red, Green = green, Blue = blue });
}
}
public IHttpActionResult Get(Color color)
{
if (color == null)
return BadRequest();
else
return Ok(color);
}
public class ColorTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
//Expecting a parameter of r,g,b, we will take this and assign to our color
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
if (value is string)
{
var rgbCodes = ((string)value).Split(',');
if (rgbCodes.Length == 3)
{
double red = 0.0;
double green = 0.0;
double blue = 0.0;
if (Double.TryParse(rgbCodes[0], out red) && Double.TryParse(rgbCodes[1], out green) && Double.TryParse(rgbCodes[2], out blue))
return new Color(){ Red = red, Green = green, Blue = blue };
}
}
if (context != null)
return base.ConvertFrom(context, culture, value);
else
return null;
}
//our Color class will convert back to RGB, separated by commas, i.e. r,g,b (100, 125.5, 50.0)
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
return ((Color)value).Red + "," + ((Color)value).Green + "," + ((Color)value).Blue;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
[TypeConverter(typeof(ColorTypeConverter))]
public class Color
{
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment