模型绑定器不适用于 JSON POST

Ada*_*abo 2 c# json http-post model-binding asp.net-core-mvc

我通过 POST 发送以下 JSON:

POST http://localhost:52873/news 

{"text":"testing","isPublic":true}
Run Code Online (Sandbox Code Playgroud)

我的控制器:

public class NewsController : Controller
{
    // GET: /<controller>/
    [HttpGet]
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Post(CreatePostCommand command)
    {
        /* ...more code... */
        return new HttpStatusCodeResult(200);
    }
}
Run Code Online (Sandbox Code Playgroud)

命令是:

public class CreatePostCommand
{
    public string Text { get; set; }
    public bool IsPublic { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的路由设置是 VS 2014 CTP 4 中 MVC 模板附带的默认设置:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default", 
        template: "{controller}/{action}/{id?}",
        defaults: new { controller = "Home", action = "Index" });

    routes.MapRoute(
        name: "api",
        template: "{controller}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)

引自ASP.NET MVC 6 入门

使用此路由模板,操作名称映射到请求中的 HTTP 动词。例如,GET 请求将调用名为 Get 的方法,PUT 请求将调用名为 Put 的方法,依此类推。{controller} 变量仍然映射到控制器名称。

这似乎对我不起作用。我收到 404 错误。我错过了这个新的 ModelBinder 什么?为什么它不绑定我的 JSON POST 消息?

Ada*_*abo 5

它工作后

  • 删除[HttpPost]属性,和
  • [FromBody]在属性类型之前添加属性。

更正后的代码:

// No HttPost attribute here!
public IActionResult Post([FromBody]CreatePostCommand command)
{
    /* ...more code... */
    return new HttpStatusCodeResult(200);
}
Run Code Online (Sandbox Code Playgroud)

  • 有趣,知道为什么吗? (2认同)