在ASP.NET Core中,使用[HttpPost]特性来标记一个方法,表示该方法只能处理POST请求。如果你的POST请求不起作用,可能是由于以下原因。
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(MyModel model)
{
// Code here
}
如果你的请求中没有包含有效的CSRF令牌,POST请求将被拒绝。
检查请求的Content-Type:确保你的POST请求的Content-Type设置为"application/x-www-form-urlencoded"或"multipart/form-data"。你可以使用Postman或类似的工具来检查请求的Content-Type。
检查请求的方法:确保你的POST请求使用正确的HTTP方法。例如,如果你使用jQuery的$.post方法发送POST请求,确保使用了正确的方法。
$.post("/Controller/Action", { data: "value" });
[HttpPost]
public IActionResult Create(MyModel model)
{
if (ModelState.IsValid)
{
// Code here
}
else
{
// Model binding failed
return BadRequest(ModelState);
}
}
确保以上步骤都正确无误后,你的POST请求应该可以正常工作了。