0

我们使用 Newtonsoft Json 转换器来反序列化 API 请求。由于我们不想接收不属于后端请求类的数据/成员,因此我们设置SerializerSettings.MissingMemberHandlingMissingMemberHandling.Error

services.AddControllers().AddNewtonsoftJson(a =>
    {
        a.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
    }

但我们最终没有收到异常,而是为 API 调用提供了一个“空”请求对象: 在此处输入图像描述

为什么我们没有异常?

4

2 回答 2

1

我不知道你是如何配置 Newtonsoft.Json 的。我做了一个工作示例。这是步骤。

  1. 添加以下 Nuget 包。

    Microsoft.AspNetCore.Mvc.NewtonsoftJson

  2. 配置它在Startup.cs.

     public void ConfigureServices(IServiceCollection services)
     {
         services.AddControllersWithViews()
             .AddNewtonsoftJson(option=>
             {
                 option.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
             });
     }
    
  3. 添加请求操作和模型。这是所有控制器代码。

    [ApiController]
    [Route("[controller]")]
    public class ValController:Controller
    {
     [AllowAnonymous]
     [HttpPost]
     public IActionResult LoginAsync([FromBody]Login login)
     {
         return Ok(login);
     }
    }
    public class Login
    {
     public string comm { get; set; }
    }
    
  4. 然后我访问操作。

在此处输入图像描述

于 2020-11-25T06:53:17.480 回答
0

I found the problem: my controller was configurered like this:

[Route("api/[controller]")]
public class MyController
{
}

Since everything was working as expected before we added the missing member setting, I did not think of the missing attribute [ApiController]. Adding this, made this controller act like the others regarding the Json serialisation!

[Route("api/[controller]")]
[ApiController]  // <- added this
public class MyController
{
}

To be sure this isn’t forgotten, we wrote a test which checks all controller classes for this attribute.

于 2020-11-25T10:53:51.560 回答