2

我通过 POST 发送以下 JSON:

POST http://localhost:52873/news 

{"text":"testing","isPublic":true}

我的控制器:

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

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

命令是:

public class CreatePostCommand
{
    public string Text { get; set; }
    public bool IsPublic { get; set; }
}

我的路由设置是 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?}");
});

引用ASP.NET MVC 6 入门

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

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

4

1 回答 1

5

它工作后

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

更正后的代码:

// No HttPost attribute here!
public IActionResult Post([FromBody]CreatePostCommand command)
{
    /* ...more code... */
    return new HttpStatusCodeResult(200);
}
于 2014-10-14T21:44:24.210 回答