【发布时间】:2021-06-27 10:36:30
【问题描述】:
我已经阅读了很多关于类似问题的问题,但似乎没有一个对我有用。
我收到 null 用于 post 操作方法中的电影对象。
这是我的控制器:
public class MovieController : Controller
{
[Route("movies/all")]
[HttpGet]
public ActionResult All()
{
List<string> movies = new List<string>();
movies.Add("Some Movie");
movies.Add("Diamond Team");
//Get movies
return Ok(movies);
}
[Route("movies/post")]
[HttpPost]
public ActionResult Post([FromBody] Movie movie)
{
Console.WriteLine(movie);
List<string> movies = new List<string>();
movies.Add(movie.title);
//Get movies
return Ok(movies);
}
public ActionResult Index()
{
return View();
}
}
这是电影类:
public class Movie
{
public string title { get; set; }
public float rating { get; set; }
public int year { get; set; }
public Movie(string title,float rating, int year)
{
this.title = title;
this.rating = rating;
this.year = year;
}
public Movie()
{
}
}
这是发布请求(使用邮递员),我尝试将 application/json 和 application/json; charset=utf-8 作为 Content-Type,但在这两种情况下我都收到了电影对象的 null:
{
"title":"Some Movie",
"rating":"1.87",
"year":"2011"
}
我该如何解决这个问题?
【问题讨论】:
-
我用 Postman 测试了您的代码,代码没有问题,因此将问题缩小到 Postman 的使用范围。您是否将请求 JSON 放入 Postman 中名为“Body”的视图中? BR
-
是的,我放入了body,并选择了“raw”选项
-
好的,您能否为来自 Postman 的以下请求设置的问题添加屏幕截图:标题、正文
-
我将它们添加到问题中
标签: c# asp.net asp.net-mvc