我有一个 .Net Core 2.1 API,它使用 EF 核心发布数据。当我从 Postman 向 http://localhost:3642/task/create 发出 POST 请求时,我收到一个 400 Bad Request 错误(由于语法错误,该请求无法完成)。经过仔细研究,我得到了一个建议来注释掉来自控制器的 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();
}
Run Code Online (Sandbox Code Playgroud)
在 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; …Run Code Online (Sandbox Code Playgroud) 当我尝试从 Postman 向 .net core 3.1 WebAPI 发出请求时,出现错误
System.InvalidOperationException:尝试激活“PaymentsAPI.Controllers.PaymentController”时无法解析类型“PaymentsAPI.Repository.PaymentService”的服务
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
services.AddDbContext<ApplicationDbContext>(o => o.UseSqlServer(Configuration.GetConnectionString("SqlSvrConn")));
services.AddTransient<IAsyncPaymentsService<PaymentDetail>, PaymentService>();
}
Run Code Online (Sandbox Code Playgroud)
IAsyncPaymentsService.cs
public interface IAsyncPaymentsService<TEntity>
{
Task<IEnumerable<TEntity>> GetAllAsync();
}
Run Code Online (Sandbox Code Playgroud)
PaymentService.cs
public class PaymentService : IAsyncPaymentsService<PaymentDetail>
{
private readonly ApplicationDbContext _dbContext;
public async Task<IEnumerable<PaymentDetail>> GetAllAsync()
{
return await _dbContext.PaymentDetails.ToListAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
PaymentController.cs
[ApiController]
[Route("[controller]")]
public class PaymentController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly PaymentService _service;
public PaymentController(ApplicationDbContext context, PaymentService …Run Code Online (Sandbox Code Playgroud)