C# Net Core-将后枚举数组接收到控制器
我正在学习.NETCore,但我不知道该怎么做 具有此控制器:C# Net Core-将后枚举数组接收到控制器,c#,asp.net-core,.net-core,C#,Asp.net Core,.net Core,我正在学习.NETCore,但我不知道该怎么做 具有此控制器: [Route("api/[controller]")] [ApiController] public class ModelController : Controller { private readonly ModelService _modelService; public ModelController(ModelService ModelService) {
[Route("api/[controller]")]
[ApiController]
public class ModelController : Controller
{
private readonly ModelService _modelService;
public ModelController(ModelService ModelService)
{
_modelService= ModelService;
}
[HttpGet]
public ActionResult<ListModel>> Get() =>
_modelService.Get();
[HttpPost]
public ActionResult<Model> Create(Model newModel)
{
_modelService.Create(newModel);
return CreatedAtRoute("GetModel", new { id = model.Id.ToString() }, model);
}
}
这个模型:
public class Model
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("Name")]
public string Name{ get; set; }
public ModelEnum[] theEnum { get; set; }
}
我怎样才能发送带有theEnum属性的请求?我正在用邮递员来测试它。当我尝试这样做时,我会收到一个HTTP 400响应,其中总是有错误
第一次测试:
{
名称:Test,
theEnum:[1,2]
}
第一错误响应
{
类型:,
标题:发生一个或多个验证错误。,
现状:400,
traceId:| 100e6798-429066a034f499f7。,
错误:{
美元.类别:[
无法将JSON值转换为System.String.Path:$.Clases | LineNumber:2 | BytePositionLine:21。
]
}}
第二次尝试:
{
"Name": "Test",
"theEnum": ["Property", "OtherProperty"]
}
第二个错误响应:
{
类型:,
标题:发生一个或多个验证错误。,
现状:400,
traceId:| 100e6799-429066a034f499f7。,
错误:{
$.Escuelas[0]:[
无法将JSON值转换为Project.ModelEnum[]。路径:$.Escuelas[0]|
行号:3 | BytePositionLine:29。
]
}}
所以我想知道,如何发送枚举类型数组的值?我做错了吗?可能验证消息说明了我需要什么,但我无法理解。您可以测试枚举1和枚举2的值。但不要为值2提供枚举 你提供
public enum ModelEnum
{
Property = 0,
OtherProperty = 1
}
属性的值为0,OtherProperty的值为1。但测试值为1和2。
在ModelEnum或测试0,1值中添加MyProperty=2
对于secon try,您需要使用StringEnumConverter我想问题在于如何将枚举数组序列化为JSON。 在Core 3.0+中,有一个新的序列化程序尚未完全支持枚举的序列化。 您需要做的是添加到您的项目中。 然后在Startup.ConfigureServices中调用AddNewtonsoftJson
请注意,枚举数组在序列化过程中会转换为数字对不起,我无法理解您的意思。你能解释一下你的答案吗?谢谢你的编辑。现在我明白你的意思了。我想StringEnumConverter是我必须编写的一个类,对吗?不,它使用的是Newtonsoft.Json.converter;但我认为它在.net核心项目中不起作用。它与.net Framework配合使用谢谢,我将尝试一下
public enum ModelEnum
{
Property = 0,
OtherProperty = 1
}