Email如果或UserName不是唯一的,我正在嘗試生成所需的錯誤訊息。使用 Swagger API,目前我得到了很大的回應,說我不能將重復值插入表中。我想用“用戶名已存在”之類的錯誤訊息替換它。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new UserEntityConfiguration());
modelBuilder.Entity<User>()
.HasIndex(u => new { u.Email, u.UserName})
.IsUnique();
}
uj5u.com熱心網友回復:
似乎沒有辦法更改OnModelCreating. 如果您接受,您可以在控制器中進行驗證并自定義錯誤訊息。
您可以參考以下代碼:
[HttpPost]
public async Task<IActionResult> Test(UserTest userTest)
{
if (ModelState.IsValid)
{
try
{
_context.UserTest.Add(userTest);
_context.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
var sqlException = GetInnerException<SqlException>(ex);
if (sqlException != null
&& (sqlException.Number == 2627 || sqlException.Number == 2601))
{
ViewData["Message"] = "Username already exists";
return View();
}
}
}
return View();
}
public TException GetInnerException<TException>(Exception exception)
where TException : Exception
{
Exception innerException = exception;
while (innerException != null)
{
if (innerException is TException result)
{
return result;
}
innerException = innerException.InnerException;
}
return null;
}
測驗結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/497172.html
