我正在尝试在.NETCore2.1中设置一个api。我一直遵循这个指南,遇到了模型没有自动验证的问题(根据微软文档)。具体来说,我想确保如果post请求是用不存在的foreignkey发送的,我应该得到badrequest响应。如果发送了正确的外键,则请求将得到正确处理。
行动:
发送post请求以添加客户ID不存在的活动。
预期:
接收请求响应
实际值:
由于未处理的dbupdateexception,api崩溃。
我的文件如下所示:
上下文.cs
public class Context : DbContext
{
public Context(DbContextOptions<Context> options)
: base(options)
{ }
public DbSet<Customer> Customers { get; set; }
public DbSet<Campaign> Campaigns { get; set; }
}
活动.cs
public class Campaign
{
public long Id { get; set; }
public long CustomerId { get; set; }
public Customer Customer { get; set; }
}
客户.cs
{
public class Customer
{
public long Id { get; set; }
public string Name { get; set; }
public List<Campaign> Campaigns { get; set; }
}
}
活动控制器.cs
[Route("api/[controller]")]
[ApiController]
public class CampaignController : ControllerBase
{
private readonly Context _context;
public CampaignController(Context context)
{
_context = context;
}
//Get Methods
[HttpPost]
public IActionResult Create(Campaign campaign)
{
_context.Campaigns.Add(campaign);
_context.SaveChanges();
return CreatedAtRoute("GetCustomer", new { id = campaign.Id }, campaign);
}
}
启动.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var connection = @"Server=(localdb)\mssqllocaldb;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<Context>(options => options.UseSqlServer(connection));
}
1条答案
按热度按时间ukqbszuj1#
不应该这样的。控制器不会验证您的db外键。这里的验证是为了验证viewmodel约束,比如
[Required]
, ...文档:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1