Asp.net 核心 MVC 发布参数始终为空 [英] Asp.net core MVC post parameter always null

查看:40
本文介绍了Asp.net 核心 MVC 发布参数始终为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 MVC 核心的新手.

I am new to MVC core.

我创建了一个带有控制器的 MVC 核心项目.此控制器具有 Get 和 Post 操作方法.如果我使用查询字符串将数据传递给 Get 方法,它工作正常,但是当我将复杂的 JSON 传递给 post 方法时,它总是显示为空.

I have created a project with MVC core which has a controller. This controller has Get and Post action methods. If i pass data to Get method using query string it works fine, but when i pass complex JSON to post method, then it always shows me null.

这是我在做什么:

发布请求

URL: http://localhost:1001/api/users
Content-Type: application/json
Body: 
{
   "Name":"UserName",
   "Gender":"Gender of the user",
   "PhoneNumber":"PhoneNumber of the user"
}

这里是 Post 操作方法

[HttpPost]
[Route("api/users")]
public async Task<IActionResult> Post([FromBody]User newUser)
{
   ...
}

当 post 请求被调用时,newUser 总是向我显示 null.如果我删除 [FromBody] 属性,那么我会收到 newUser 对象,但它的所有字段都为空.

When post request is called, then newUser always shows me null. And if i remove [FromBody] attribute then i receive newUser object but all of its fields are null.

请在这个问题上帮助我并指导我.

Please help me and guide me in this issue.

已编辑

这是我的用户

public class User{

   public int Id { get; set; }
   public string Name { get; set; }
   public string Gender { get; set; }
   public string PhoneNumber { get; set; }
}

我做了与描述相同的此处 用于 json 数据,但仍接收空值.

I had done same as described here for json data, but still receives null.

推荐答案

这可能与处理空值的方式有关.在 AddJsonOptions 中将 NullValueHandling 设置为 Ignore 并查看是否有效.

This could be because of how the null values are being handled. Set NullValueHandling to Ignore in AddJsonOptions and see if that works.

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .AddJsonOptions(jsonOptions=>
        {
            jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        });
}

这篇关于Asp.net 核心 MVC 发布参数始终为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆