WebAPI数据框架忽略了自定义EnumConverter
我有以下enum
和enumConverter
:
[TypeConverter(typeof(MyEnumConverter))]
public enum MyEventType {
Unknown,
URLEvent
}
public class MyEnumConverter : EnumConverter
{
public MyEnumConverter(Type type) : base(type)
{
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
var enumString = (string)value;
return EnumExtensions.GetValueFromDescription(enumString, EnumType);
}
return base.ConvertFrom(context, culture, value);
}
}
我还有一个WebAPI控制器,该webAPI控制器接受一个对象,该对象包含上述枚举类型的属性:
[Route("api/v1/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
[Route("events")]
[HttpPost]
public IActionResult HandlePost([FromBody] MyEvent myEvent)
{
// Do whatever here
}
}
public class MyEvent
{
public MyEventType eventType {get; set;}
}
但是,如果i post
{“ eventType”:“ urlevent”}
到控制器,我得到一个错误:“无法转换JSON值... convertfrom()我可以看到它永远不会被调用。
我需要做什么才能使Web API数据限制使用我的EnumConverter?
I have the following enum
and EnumConverter
:
[TypeConverter(typeof(MyEnumConverter))]
public enum MyEventType {
Unknown,
URLEvent
}
public class MyEnumConverter : EnumConverter
{
public MyEnumConverter(Type type) : base(type)
{
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
var enumString = (string)value;
return EnumExtensions.GetValueFromDescription(enumString, EnumType);
}
return base.ConvertFrom(context, culture, value);
}
}
I also have a WebAPI controller that accepts an object that contains a property of the above enum type:
[Route("api/v1/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
[Route("events")]
[HttpPost]
public IActionResult HandlePost([FromBody] MyEvent myEvent)
{
// Do whatever here
}
}
public class MyEvent
{
public MyEventType eventType {get; set;}
}
However, if I POST
{"eventType" : "URLEvent"}
to the controller, I get an error: "The JSON value could not be converted ..." Placing a break-point in ConvertFrom()
I can see that the it is never being called.
What do I need to do to get the Web API databinding to use my EnumConverter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是解决您当前问题的两种替代方法:
第一个:
System.Text.json serialization
:可以找到该文档在这里。
第二:
newtonsoft.json
,然后:
测试结果:
Here are two alternatives to solve your current problem:
First:
System.Text.Json serialization
:The documentation can be found here.
Second:
Newtonsoft.Json
And then:
Test Result: