枚举错误时requestModel为null

发布于 2025-01-27 01:11:36 字数 446 浏览 1 评论 0原文

如果您有此枚举:

public enum MyEnum
{
    Value1,
    Value2
}

并且此请求:

{
   "myEnum" : "WrongValue",
   "name" : "MyName"
}

在控制器中:

public async Task<ActionResult> RequestAsync(
        [FromBody] MyRequest myRequest)
    {
    }

MyRequest为无效。

但是如果您使用;

{
   "myEnum" : "Value1",
   "name" : "MyName"
}

它不是零。

If you have this enum :

public enum MyEnum
{
    Value1,
    Value2
}

And this Request :

{
   "myEnum" : "WrongValue",
   "name" : "MyName"
}

In the controller :

public async Task<ActionResult> RequestAsync(
        [FromBody] MyRequest myRequest)
    {
    }

myRequest is null.

But if you use ;

{
   "myEnum" : "Value1",
   "name" : "MyName"
}

It is not null.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

原野 2025-02-03 01:11:36

是的,当无效的枚举值传递给模型时,您将收到整个请求模型为null

,但我们可以利用microsoft.aspnetcore.mvc.modelstate检查请求模型是否有效,

public async Task<ActionResult> RequestAsync(MyRequest myRequest)
{
     if (!ModelState.IsValid)
     {
         return BadRequest(ModelState);
     }

     // api implementation ...
}

这将从ModelState用于响应中无效的枚举属性如下

{
  "myRequest": [
    "The myRequest field is required."
  ],
  "$.Protocol": [
    "The JSON value could not be converted to Namespace.MyEnum. Path: $.Protocol | LineNumber: X | BytePositionInLine: XX."
  ]
}

Yes correct when invalid Enum value passed to model, you will receive entire request model as null

but we can leverage Microsoft.AspNetCore.Mvc.ModelState to check whether request model is valid or not

public async Task<ActionResult> RequestAsync(MyRequest myRequest)
{
     if (!ModelState.IsValid)
     {
         return BadRequest(ModelState);
     }

     // api implementation ...
}

this will return error from ModelState for invalid enum property in response as below

{
  "myRequest": [
    "The myRequest field is required."
  ],
  "$.Protocol": [
    "The JSON value could not be converted to Namespace.MyEnum. Path: $.Protocol | LineNumber: X | BytePositionInLine: XX."
  ]
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文