首页 > 解决方案 > Net Core - 将 POST 枚举数组接收到控制器

问题描述

我正在学习 .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 响应,总是有错误

第一个测试: { "Name": "Test", "theEnum": [1, 2] }

第一个错误响应

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

第二次尝试:

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

第二个错误响应:

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

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

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

解决方案


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

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

值为0的属性和值为1的OtherProperty 。但测试值12。添加或测试秒MyProperty = 2的0,1 值 尝试您需要使用 StringEnumConverterModelEnum


推荐阅读