【问题标题】:Net Core - Receive POST Enum Array to a controllerNet Core - 将 POST 枚举数组接收到控制器
【发布时间】:2020-10-01 02:23:51
【问题描述】:

我正在学习 .NET Core,但我不知道该怎么做。

拥有这个控制器:

[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 enum ModelEnum
{
    Property = 0,
    OtherProperty = 1
}

还有这个模型:

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 响应

第一次测试: { “名称”:“测试”, "theEnum": [1, 2] }

第一个错误响应

{ “类型”:“https://www.rfc-editor.org/rfc/rfc7231#section-6.5.1”, "title": "出现一个或多个验证错误。", “状态”:400, "traceId": "|100e6798-429066a034f499f7.", “错误”:{ “$.Classes”:[ “无法将 JSON 值转换为 System.String。路径:$.Classes | LineNumber:2 | BytePositionInLine:21。” ] } }

第二次尝试:

{
    "Name": "Test",
    "theEnum": ["Property", "OtherProperty"]
}

第二个错误响应:

{ “类型”:“https://www.rfc-editor.org/rfc/rfc7231#section-6.5.1”, "title": "出现一个或多个验证错误。", “状态”:400, "traceId": "|100e6799-429066a034f499f7.", “错误”:{ “$.Escuelas[0]”:[ “无法将 JSON 值转换为 Project.ModelEnum[]。路径:$.Escuelas[0] | 行号:3 | BytePositionInLine:29。” ] } }

所以我想知道,如何发送 Enum 类型数组的值?我做错了吗?也许验证消息说的是我需要的,但我无法理解。

【问题讨论】:

  • 你需要有[JsonConverter(typeof(StringEnumConverter))] public enum ModelEnum
  • 我猜StringEnumConverter是我必须要写的一个类,这样对吗?
  • 不,它在using Newtonsoft.Json.Converters;
  • 但我认为它不适用于 .net 核心项目。它适用于 .net 框架

标签: c# asp.net-core .net-core


【解决方案1】:

您测试枚举 1 和 2 的值。但不提供值 2 的枚举
你提供

public enum ModelEnum
{
    Property = 0,
    OtherProperty = 1
}

值为 0 的属性和值为 1 的 OtherProperty。但测试值 12。 在ModelEnum 中添加MyProperty = 2 或测试0,1 值
第二次尝试你需要使用 StringEnumConverter

【讨论】:

  • 对不起,听不懂。你能解释一下你的答案吗?
  • 感谢您的编辑。现在我明白你了。我会试试的。
【解决方案2】:

我猜问题在于将枚举数组序列化为 JSON。 在 Core 3.0+ 中有一个新的序列化器,它还不能完全支持枚举的序列化。 您需要做的是将Newtonsoft.Json 添加到您的项目中。 然后在 Startup.ConfigureServices 中调用 AddNewtonsoftJson()。

注意枚举数组在序列化过程中会转换为数字

【讨论】:

  • 谢谢,我试试看
猜你喜欢
  • 1970-01-01
  • 2019-12-31
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多