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

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

问题描述

我是MVC核心的新手.

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

这是我在做什么:

发布请求

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

这是发布"操作方法

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

调用发帖请求时, newUser 始终显示为空.而且,如果我删除 [FromBody] 属性,则会收到newUser对象,但其所有字段均为空.

请帮助我,并在此问题上为我提供指导.

已编辑

这是我的 User

public class User{

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

我已经按照解决方案

这可能是因为如何处理空值.在AddJsonOptions中将NullValueHandling设置为Ignore,看看是否可行.

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

I am new to MVC core.

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.

Here what i am doing:

Post Request

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

Here is the Post action method

[HttpPost]
[Route("api/users")]
public async Task<IActionResult> Post([FromBody]User 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.

EDITED

Here is my User class

public class User{

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

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

解决方案

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发布参数始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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