如何在ASP.NET核心MVC中处理AJAX异常并显示自定义错误页面?

如何在ASP.NET核心MVC中处理AJAX异常并显示自定义错误页面?,ajax,asp.net-core,model-view-controller,.net-5,Ajax,Asp.net Core,Model View Controller,.net 5,我刚刚开始使用ASP.NET核心MVC和web开发,我正在努力理解如何显示AJAX调用中的错误页面 我想做的是在Ajax调用失败时显示一个带有错误消息的自定义页面。到目前为止,我有以下代码,当我在控制器中抛出异常时,它会将我带到我的500页,但是我如何让它在该页上显示异常消息呢 StartUp.cs中间件: if (env.IsDevelopment()) { app.UseDeveloperExceptionPage();

我刚刚开始使用ASP.NET核心MVC和web开发,我正在努力理解如何显示AJAX调用中的错误页面

我想做的是在Ajax调用失败时显示一个带有错误消息的自定义页面。到目前为止,我有以下代码,当我在控制器中抛出异常时,它会将我带到我的500页,但是我如何让它在该页上显示异常消息呢

StartUp.cs
中间件:

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseStatusCodePagesWithReExecute("/Error/Error", "?Code={0}");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
错误控制器:

    public IActionResult Error(int? Code = null)
    {
        if (Code.HasValue)
        {
            if (Code.Value == 404 || Code.Value == 500)
            {
                var viewName = Code.ToString();
                return View(viewName);
            }
        }

        return View();
    }
AJAX调用:

// Use ajax call to post to the controller with the data
$.ajax({
        type: "POST",
        url: "/Renewals/GenerateQuotes",
        data: { selectedContractIds: ids },
        success: function (response) {
                     // Show success and refresh the page
                     Toast.fire({
                                icon: 'success',
                                title: 'Quotes Generated'
                            }).then(function () {
                                location.reload();
                            });
        },
        error: function (xhr, status, error) {
               // Response message
               var response = xhr.responseText;
               window.location.href = '@Url.Action("Error", "Error")?Code=' + xhr.status;
        }
})

通常我们在页面的一小部分显示ajax请求的错误,例如:a…,或者通过屏幕某个角落的弹出工具提示。。。为什么你想要一个完整的错误页面?如果希望在当前页面中嵌入一些富HTML预定义的自定义错误页面,可以将该部分HTML作为对ajax请求的响应返回,以便显示该页面。该响应可以通过
xhr.responseText
获得。谢谢,我只是认为查看内部应用程序的错误会很有用。我会看看这个选项。