Skip to content

Instantly share code, notes, and snippets.

@pmhsfelix
Created August 23, 2014 17:22
Show Gist options
  • Save pmhsfelix/008a393013294e6223c1 to your computer and use it in GitHub Desktop.
Save pmhsfelix/008a393013294e6223c1 to your computer and use it in GitHub Desktop.
Can_use_TypeConverter_to_handle_simple_values
// based on http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
// and http://blogs.msdn.com/b/jmstall/archive/2012/04/20/how-to-bind-to-custom-objects-in-action-signatures-in-mvc-webapi.aspx
public class Can_use_TypeConverter_to_handle_simple_values
{
[TypeConverter(typeof(LocationTypeConverter))]
public class Location
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public static Location TryParse(string input)
{
var parts = input.Split(',');
if (parts.Length != 2)
{
return null;
}
int x, y;
if (int.TryParse(parts[0], out x) && int.TryParse(parts[1], out y))
{
return new Location { Latitude = x, Longitude = y };
}
return null;
}
public override string ToString()
{
return string.Format("{0},{1}", Latitude, Longitude);
}
}
public class ResourceController : ApiController
{
public async Task<HttpResponseMessage> Get(int id, Location location)
{
Assert.Equal(123, id);
Assert.NotNull(location);
Assert.Equal(1, location.Latitude);
Assert.Equal(2, location.Longitude);
return new HttpResponseMessage()
{
Content =
new StringContent(Url.Link("ApiDefault",
new
{
controller = "resource",
id = 123,
location = new Location {Latitude = 3, Longitude = 4}
}))
};
}
}
[Fact]
public async Task Run()
{
var client = new TestConfig<ResourceController>().GetClient();
client.DefaultRequestHeaders.Host = "example.net";
var res = await client.GetAsync("http://example.net/resource/123?location=1,2");
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
var url = await res.Content.ReadAsStringAsync();
Assert.Equal("http://example.net/resource/123?location=3%2C4", url);
}
public class LocationTypeConverter : 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)
{
return Location.TryParse((string)value);
}
return base.ConvertFrom(context, culture, value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment