不能在与 REFERENCE 约束冲突的 DELETE 语句中使用 Tempdata,

问题描述 投票:0回答:1

当产品仍然与数据库中的许多表相关时,我尝试删除该产品并显示错误消息。这里是代码:

[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>
}

但它总是这样显示img。我已经在 Program.cs

中使用了 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 以错误的方式?我真的很感激任何指示。谢谢你

c# asp.net-mvc asp.net-core razor-pages
1个回答
0
投票

catch
声明中,您有一行
throw

catch (DbUpdateException ex)
{
    //....
    throw;
}

它追溯异常,该异常被asp.net core异常过滤器捕获并显示错误页面。

删除捕获中的

throw

© www.soinside.com 2019 - 2024. All rights reserved.