首页 > 解决方案 > 如何使 dot.net 核心应用程序显示错误而不是发出空白的 500 错误页面

问题描述

这是我在 startup.cs 中的功能。

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        app.UseCors(builder =>
        builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin());

        app.UseMvc(routes =>
              {
                  routes.MapRoute("apiActions", "api/{controller}/{action}");
              });


  app.UseDeveloperExceptionPage();
  app.UseDatabaseErrorPage();

  app.Use(async (context, next) =>
              {
                  await next();
                  if (context.Response.StatusCode == 404 &&
                     !Path.HasExtension(context.Request.Path.Value) &&
                     !context.Request.Path.Value.StartsWith("/api/"))
                  {
                      context.Request.Path = "/index.html";
                      await next();
                  }
              });
        app.UseMvcWithDefaultRoute();
        app.UseDefaultFiles();
        app.UseStaticFiles();


  app.UseStaticFiles(new StaticFileOptions()
        {
            // FileProvider = new PhysicalFileProvider(
            // Path.Combine(Directory.GetCurrentDirectory(), "Images")),
            // RequestPath = new PathString("/Images")
        });
    }

如何查看响应中的错误?每当我将错误扔到控制器中时,我都希望将错误发送到浏览器。

例如,如果我这样做:

    [HttpGet]
public string GetStartUpURL(string gameID, int userId, string mode)
{
  throw new Exception("Test");
 return null;
}

我希望返回一个错误而不是带有 500 代码的空白正文响应。

我使用的是 web api 核心,而不是 mvc。

标签: asp.net-core-2.0

解决方案


对于您的问题,这是由于您放置Error Handling在之前引起的UseMvc。为了在此应用程序中捕获错误,您应该放在Error Handling Middleware第一个。

尝试修改您的Configure如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
  app.UseDeveloperExceptionPage();
  app.UseDatabaseErrorPage();

  app.Use(async (context, next) =>
              {
                  await next();
                  if (context.Response.StatusCode == 404 &&
                     !Path.HasExtension(context.Request.Path.Value) &&
                     !context.Request.Path.Value.StartsWith("/api/"))
                  {
                      context.Request.Path = "/index.html";
                      await next();
                  }
              });
        app.UseMvcWithDefaultRoute();
        app.UseDefaultFiles();
        app.UseStaticFiles();


  app.UseStaticFiles(new StaticFileOptions()
        {
            // FileProvider = new PhysicalFileProvider(
            // Path.Combine(Directory.GetCurrentDirectory(), "Images")),
            // RequestPath = new PathString("/Images")
        });
app.UseCors(builder =>
        builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin());

        app.UseMvc(routes =>
              {
                  routes.MapRoute("apiActions", "api/{controller}/{action}");
              });
    }

如果您想自定义错误响应而不是使用UseDeveloperExceptionPage. 您可以尝试以下方法:

app.UseExceptionHandler(
               new ExceptionHandlerOptions
               {
                   ExceptionHandler = async context =>
                   {
                       context.Response.ContentType = "text/html";
                       var ex = context.Features.Get<IExceptionHandlerFeature>();
                       if (ex != null)
                       {
                           var err = $"<h1>Error: {ex.Error.Message}</h1>";
                           await context.Response.WriteAsync(err);
                       }
                   }
               });

推荐阅读