【发布时间】: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