我遇到的问题与https://github.com/aspnet/AspNetCore/issues/4008有点相似,我想在所有可能的情况下寻求帮助。
对于网址http://localhost:51049/api/values/proof_of_address,路由应在下面的枚举中将proof_of_address评估为ProofOfAddress。
我试图按照上面链接中的示例进行操作,但是无论我在url中输入什么内容,我都会在枚举中获得第一个值。我的代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(opt =>
{
opt.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
opt.SerializerSettings.Converters.Add(new StringEnumConverter());
});
}
[HttpGet("{documenttype}")]
public ActionResult<string> Get([FromRoute] DocumentType documenttype)
{
return documenttype.ToString();
}
public class CustomEnumConverter<T> : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var s = value as string;
if (string.IsNullOrEmpty(s))
{
return null;
}
return JsonConvert.DeserializeObject<T>(@"""" + value.ToString() + @"""");
}
}
[TypeConverter(typeof(CustomEnumConverter<DocumentType>))]
public enum DocumentType
{
[EnumMember(Value = "passport")]
Passport,
[EnumMember(Value = "proof_of_address")]
ProofOfAddress
}
谢谢您的任何帮助。
答案 0 :(得分:0)
您需要覆盖CanConvertFrom
才能返回true
public class CustomEnumConverter<T> : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return true;
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var s = value as string;
if (string.IsNullOrEmpty(s))
{
return null;
}
return JsonConvert.DeserializeObject<T>(@"""" + value.ToString() + @"""");
}
}