2014-04-01 29 views
2

我已經創建了一個自定義類型來允許我驗證國家/地區代碼,但我在使用此類型作爲WebAPI調用的參數時遇到了問題。作爲參數傳遞的自定義類型

我的自定義類型驗證字符串,然後使用隱式運算符分配自己;

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(); 
    } 
} 

WebAPI調用;

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

可以解決這個問題;

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

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

是否可以改變我的自定義類型,以便通過WebAPI參數調用實例化?

回答

2

使用的類型轉換器

[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); 
    } 
} 

然後

[HttpGet] 
public HttpResponseMessage Get(CountryCode countryCode) 

將工作

+0

我會建議雖然因爲其他開發人員期望蒙上永遠不會返回null不使用隱式轉換 – LostInComputer

相關問題