【发布时间】:2019-09-07 11:44:51
【问题描述】:
我有一个使用 EF 核心发布数据的 .Net Core 2.1 API。当我从 Postman 向 http://localhost:3642/task/create 发出 POST 请求时,我收到 400 错误请求错误(由于语法错误,请求无法完成)。在四处挖掘后,我得到了一个注释掉的建议来自控制器的 ValidateAntiForgery 令牌。当我通过此更改传递邮递员的请求时,我收到 200 Ok 状态消息,但没有数据被提交到 Sql Server 中的表。我应该在我的 API 中配置什么,我还缺少什么?
我的控制器如下所示:
[HttpPost]
// [ValidateAntiForgeryToken]
public async Task<IActionResult>
Create([Bind("Assignee,Summary,Description")] TaskViewModel taskViewModel)
{
if (ModelState.IsValid)
{
_context.Add(taskViewModel);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View();
}
在 TaskViewModel.cs 我有:
public class TaskViewModel
{
[Required]
public long Id { get; set; }
[Required(ErrorMessage = "Please provide Task Summary")]
[Display(Name = "Summary")]
public string Summary { get; set; }
[Required(ErrorMessage = "Please enter task description")]
[Display(Name = "Description")]
public string Description { get; set; }
[Required(ErrorMessage = "Please select Assignee")]
[Display(Name = "Assign To")]
public string Assignee { get; set; }
}
这是我在 Postman 中的有效载荷:
{
"Assignee": "Ed tshuma",
"Summary": "Finish reconciliations",
"Description": "collate all the pending data"
}
【问题讨论】:
-
Id是必需的,并且不存在于显示的有效负载中。这会导致ModelState.IsValid返回false并且不提交。
标签: entity-framework asp.net-core postman