asp.net-core-2.0 - 如何使 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。
解决方案
对于您的问题,这是由于您放置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);
}
}
});
推荐阅读
- javascript - 在 IntelliJ 中阻止 Typescript 自动完成
- algorithm - 在这种情况下,“给出整体运行时间”是什么意思?
- javascript - 如何将字符串转换为对象以便能够将其作为函数参数传递
- jquery-terminal - 反转 JQuery-Terminal 的流程
- elastic-stack - ELK,本地机器上的 Filebeat 设置,Logstash 不工作,伐木工人协议错误
- php - PHP表格行编号
- sql - 如何在 SAS EG 中获取行号列以简化按该唯一编号选择行?我想使用 PROC SQL 语法
- c# - 结构为 ReadOnlyMemory
表示 - node.js - 调用 Rest API 时 Node.js Discord 机器人消息为空
- racket - 球拍有点不一致