Asp.net-Mvc

Asp.net core MVC post 參數始終為空

  • July 19, 2016

我是 MVC 核心的新手。

我創建了一個帶有 MVC 核心的項目,它有一個控制器。此控制器具有 Get 和 Post 操作方法。如果我使用查詢字元串將數據傳遞給 Get 方法,它可以正常工作,但是當我將復雜的 JSON 傳遞給 post 方法時,它總是顯示為空。

這是我在做什麼:

發布請求

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)
{
  ...
}

當呼叫發布請求時,newUser總是顯示為空。如果我刪除**[FromBody]**屬性,那麼我會收到 newUser 對象,但它的所有欄位都是空的。

請幫助我並指導我解決這個問題。

已編輯

這是我的使用者

public class User{

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

對於 json 數據,我已經完成了與此處所述相同的操作,但仍然收到 null。

這可能是因為如何處理空值。在 AddJsonOptions 中將 NullValueHandling 設置為 Ignore 並查看是否有效。

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

引用自:https://stackoverflow.com/questions/38455954