首页 > 解决方案 > 如何正确处理 ASP.NET Core MVC 中的 AJAX 错误?

问题描述

背景:

我在 ASP.NET Core 2.2 MVC 应用程序中设置错误处理。在开发环境中,我使用app.UseDeveloperExceptionPage();, 而在生产环境中 - app.UseExceptionHandler("/Error/Index");。在基于环境的非 AJAX(常规表单提交)请求期间,我被导航到正确的错误页面。

如果在 AJAX 请求期间服务器发生异常,我希望应用程序根据环境显示正确的错误页面。

正如您在下面的代码示例中所见,我已经设置了上面描述的所有内容。

问题/担忧:

虽然这可行(尽管仍然必须完成 TODOInitializeGlobalAjaxEventHandlers功能),但我有一些担忧。

在 MVC 中使用非 AJAX 调用,感觉就像有一种“官方/正确”的方式来使用app.UseDeveloperExceptionPage();and app.UseExceptionHandler("/Error/Index");,它会自动将程序重定向到错误页面。然而,对于错误处理的 AJAX 端,我没有那么自信,因为我将它与我研究过的不同解决方案的部分拼凑在一起。我担心我不知道会出什么问题。

问题:

这是在 MVC 中处理 AJAX 请求期间错误的正确方法吗?这种设置可能会出现问题吗?这是否有任何不当或与共同标准相去甚远?

代码:

Startup.cs > 配置方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //using build config to use the correct error page: https://stackoverflow.com/a/62177235/12300287
    //Reason why we don't use environmental variables is because we can't guarantee access to clients' 
    //machines to create them.
#if (DEVELOPMENT || STAGING)
    app.UseDeveloperExceptionPage();
#else
    app.UseExceptionHandler("/Error/Index");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
#endif

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    //app.UseCookiePolicy();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=UserAccess}/{action=Index}/{id?}");
    });
}

错误控制器.cs:

public class ErrorController : Controller
{
    [AllowAnonymous]
    public IActionResult Index()
    {
        IExceptionHandlerPathFeature exceptionDetails = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
        Exception exception = exceptionDetails?.Error; // Here will be the exception details.

        Error model = new Error();
        model.ID = exception.HResult;
        model.Message = exception.Message;
        model.Path = exceptionDetails.Path;

        return View(model);
    }
}

全局 AJAX 错误事件处理程序(if语句是处理身份验证):

function InitializeGlobalAjaxEventHandlers() {
    $(document).ajaxError(function (event, xhr, ajaxSettings, thrownError) {
        //status is set in the [AuthorizeAjax] action filter if user isn't authenticated
        if (xhr.status == 403) {
            var response = $.parseJSON(xhr.responseText);
            window.location = response.redirectUrl;
        }

        //the document HTML is replaces by responseText value, which contains the HTML of error page
        document.write(xhr.responseText);

        //TODO: will need to display an error page if responseText is empty, which
        //can happen if an AJAX request doesn't reach the server (for example: if URL is incorrect).
    });
}

标签: javascriptc#ajaxasp.net-coreasp.net-core-mvc

解决方案


这是在 MVC 中处理 AJAX 请求期间错误的正确方法吗?这种设置可能会出现问题吗?这是否有任何不当或与共同标准相去甚远?

据我所知,在 ASP.NET Core MVC 项目中没有统一/官方的方式来处理 Ajax 错误。

通常我们会在Ajax请求失败时通过Ajax错误回调函数显示具体的确认消息/内容,而不是直接向客户端用户显示详细的异常信息,这样有助于获得更好的客户体验。

如果您有特定要求需要在 Ajax 请求失败时显示开发人员异常页面/自定义错误页面,就像您所做的那样,您可以使用全局错误处理程序将返回responseText的内容动态写入 HTML 文档。document.write(xhr.responseText);


推荐阅读