首页 > 解决方案 > Web api 和 Mvc Razor 中的 Dotnet Core 错误处理

问题描述

在我的 Web 应用程序中,我有 Web API 和普通的 MVC,我为 httpResponse 创建了一个扩展

 public static void ShowApplicationError(this HttpResponse response, string exceptionMessage,string innerException)
    {
        var result = JsonConvert.SerializeObject(new { error = exceptionMessage ,detail=innerException });
        response.HttpContext.Response.WriteAsync(result);
    }

并在 startup.cs 中用于异常处理。

app.UseExceptionHandler(builder =>
            {
                builder.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        context.Response.ShowApplicationError(error.Error.Message, error.Error.InnerException.Message);
                    }
                });
            });

像这样。它对两者都很好。我想区分每个请求的错误。我不想显示 mvc 的 json 错误结束我该怎么做。

标签: c#asp.net-coreasp.net-core-mvc

解决方案


这种情况的最佳解决方案是更好地分离您的关注点。使您的 api 成为与您的 MVC 应用程序分开的 csproj。它还将为您提供以后部署的灵活性。如果这是现有代码而不是新代码,我会游说将其重构为单独的 api 项目。


推荐阅读