[英]Net Core - Receive POST Enum Array to a controller
我正在學習 .NET Core,但我不知道該怎么做。
擁有這個 controller:
[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
}
而這個 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
的請求? 我正在使用 postman 來測試它。 當我嘗試這樣做時,我收到一個 HTTP 400 響應,總是有錯誤
第一個測試: { "Name": "Test", "theEnum": [1, 2] }
第一個錯誤響應
{ "type": " https://tools.ietf.org/html/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://tools.ietf.org/html/rfc7231#section-6.5.1 ", "title": "出現一個或多個驗證錯誤。", "status": 400, "traceId" : "|100e6799-429066a034f499f7.", "errors": { "$.Escuelas[0]": [ "JSON 值無法轉換為 Project.ModelEnum[]。路徑:$.Escuelas[0] | LineNumber: 3 | BytePositionInLine:29。” ] } }
所以我想知道,如何發送 Enum 類型數組的值? 我做錯了嗎? 也許驗證消息說的是我需要的,但我無法理解。
您測試枚舉 1 和 2 的值。但不提供值 2 的枚舉
你提供
public enum ModelEnum
{
Property = 0,
OtherProperty = 1
}
值為0的屬性和值為1的 OtherProperty。 但測試值1和2 。 在ModelEnum
中添加MyProperty = 2
或測試 0,1 值
第二次嘗試你需要使用 StringEnumConverter
我想問題在於將枚舉數組序列化為 JSON。 在 Core 3.0+ 中有一個新的序列化器,它還不能完全支持枚舉的序列化。 您需要做的是將Newtonsoft.Json添加到您的項目中。 然后在 Startup.ConfigureServices 中調用 AddNewtonsoftJson()。
請注意,枚舉數組在序列化期間轉換為數字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.