wonea
wonea

Reputation: 4969

Custom Types passed as parameter

I've created a custom type to allow me verify a country code, but I'm having trouble using this as a parameter for WebAPI call.

My custom Type which validates a string then assigns itself using the implicit operator;

public class CountryCode
{
    private readonly string _CountryCode;
    private CountryCode(string countryCode)
    {
        _CountryCode = countryCode;
    }
    public static implicit operator CountryCode(string countryCode)
    {
        return (countryCode.Length == 3) ? new CountryCode(countryCode) : null;
    }
    public override string ToString()
    {
        return _CountryCode.ToString();
    }
}

The WebAPI call;

[HttpGet]
public HttpResponseMessage Get(CountryCode countryCode)
{
    // countryCode is null
}

It's possible to work around this;

[HttpGet]
public HttpResponseMessage Get(string countryCode)
{
    CountryCode countrycode = countryCode;
    return Get(countrycode);
}

private HttpResponseMessage Get(CountryCode countryCode)
{
    // countryCode is valid
}

Is it possible to alter my custom type so it is instantiated by the WebAPI parameter call?

Upvotes: 2

Views: 99

Answers (1)

LostInComputer
LostInComputer

Reputation: 15420

Use type converters

[TypeConverter(typeof(CountryCodeConverter))]
public class CountryCode
{
    ...
}

public class CountryCodeConverter : 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 && value != null)
        {
            return (CountryCode)((string)value);
        }
        return base.ConvertFrom(context, culture, value);
    }
}

then

[HttpGet]
public HttpResponseMessage Get(CountryCode countryCode)

will work

Upvotes: 2

Related Questions