繁体   English   中英

Web API POST 请求 object 始终为 null

[英]Web API POST request object is always null

我正在使用.Net Core API 2.1 我的 Controller 中有这个:

[Route("Invoke")]
        [HttpPost]
        public IActionResult Invoke(Student studentDetails)
        {
            DetailsResponse objResponse;
            if(ModelState.IsValid)
                {
                  objResponse= GetDetails(studentDetails);
                }
              return OK(objResponse);  
        }

我正在尝试从 Postman 调用 Invoke 操作方法,请求正文为

{"student": {"name":"John Doe", "age":18, "country":"United States of America"}}

这个 object 在 controller 中始终是 null。 如果我尝试从 Postman 调用操作方法,请求正文为

{"name":"John Doe", "age":18, "country":"United States of America"}

object 在这里有数据并且工作正常。 我的问题是使用根节点调用操作,如下所示

{"student": {"name":"John Doe", "age":18, "country":"United States of America"}}

有没有可能实现这一目标?

根据您可以使用的框架

public IActionResult Invoke([FromBody]Student studentDetails)

将会发生的情况是 model 绑定将尝试和 map json 到 ZA2F2ED4F8EBC2CBB14C21A29DC40 您已指定。

问题是您的第二次尝试完全模仿了您的学生 class,这就是它映射到学生的原因。

{"name":"John Doe", "age":18, "country":"United States of America"}

如果您想收到 object 字段“学生”填充学生 json,您可以创建另一个 class StudentWrapper 或 InvokeParameters 或类似的学生字段。

但是如果你真的不需要它,你最好不要这样做。 通常它不是必须的,应该省略。 仅当您在 API 操作中收到多个模型(例如 Student)时才有用。

{"name":"John Doe", "age":18, "country":"United States of America"}

这是默认 JsonInputFormatter 中 model Student可接受的 json。您要传递的是不可接受的 json Student ,您需要自定义 JsonInputFormatter 以满足您的要求:

public class CustomJsonInputFormatter : JsonInputFormatter
{
    public CustomJsonInputFormatter(ILogger logger, JsonSerializerSettings serializerSettings, ArrayPool<char> charPool, ObjectPoolProvider objectPoolProvider, MvcOptions options, MvcJsonOptions jsonOptions) : base(logger, serializerSettings, charPool, objectPoolProvider, options, jsonOptions)
    {

    }
    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
    {
        var request = context.HttpContext.Request;
        using (var reader = new StreamReader(request.Body))
        {
            string content = await reader.ReadToEndAsync();
            JObject jo = JObject.Parse(content);
            Student student = jo.SelectToken("student", false).ToObject<Student>();
            return await InputFormatterResult.SuccessAsync(student);
        }
    }
}

启动.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        var serviceProvider = services.BuildServiceProvider();
        var jsonInputLogger = serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger<CustomJsonInputFormatter>();
        var jsonOptions = serviceProvider.GetRequiredService<IOptions<MvcJsonOptions>>().Value;
        var charPool = serviceProvider.GetRequiredService<ArrayPool<char>>();
        var objectPoolProvider = serviceProvider.GetRequiredService<ObjectPoolProvider>();

        var customJsonInputFormatter = new CustomJsonInputFormatter(
                    jsonInputLogger,
                    jsonOptions.SerializerSettings,
                    charPool,
                    objectPoolProvider,
                    options,
                    jsonOptions
            );
        options.InputFormatters.Insert(0, customJsonInputFormatter);
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

结果: 在此处输入图像描述

另一种方式:

{"student": {"name":"John Doe", "age":18, "country":"United States of America"}}

此 json 适用于以下 model:

public class Student
{
    public int Age { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

public class Test
{
    public Student student { get; set; }
}

行动:

[HttpPost]
public IActionResult Invoke(Test studentDetails)
{
   //...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM