当产品仍然与数据库中的许多表相关时,我尝试删除该产品并显示错误消息。这里是代码:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
if (_context.Products == null)
{
return Problem("Entity set 'ShoeContext.Products' is null.");
}
var product = await _context.Products.FindAsync(id);
if (product != null)
{
_context.Products.Remove(product);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
if (ex.InnerException?.InnerException is SqlException sqlEx)
{
TempData["ErrorMessage"] = "Cant't Delete This Product";
return RedirectToAction("Index");
}
throw;
}
return RedirectToAction("Index");
}
return RedirectToAction(nameof(Index));
}
在 Index.cshtml 中:
@if (TempData["ErrorMessage"] != null)
{
<div class="alert alert-danger">
@TempData["ErrorMessage"]
</div>
}
中使用了 UseSession
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;// Set the session timeout as needed
options.Cookie.IsEssential = true;
});
有人知道问题所在吗?我是否使用了 tempdata 或 try catch 以错误的方式?我真的很感激任何指示。谢谢你
在
catch
声明中,您有一行 throw
:
catch (DbUpdateException ex)
{
//....
throw;
}
它追溯异常,该异常被asp.net core异常过滤器捕获并显示错误页面。
删除捕获中的
throw
。