Coo*_*eze 10 c# exception http-status-codes asp.net-core-mvc asp.net-core
我想有一个错误页面,根据提供的查询字符串显示一个稍微不同的错误消息给用户.
在创建新的asp.net 5项目时,我注意到Startup.cs文件中的以下代码.
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
Run Code Online (Sandbox Code Playgroud)
发生异常时,我能够显示正确的错误页面.我的问题是,它似乎只能捕获我的应用程序中尚未处理的错误,即状态代码始终为500
.它是否正确?
要处理404
错误,我使用以下代码:
app.UseStatusCodePagesWithReExecute("/Error/{0}");
Run Code Online (Sandbox Code Playgroud)
我的控制器实现为:
[HttpGet("{statusCode}")]
public IActionResult Error(int statusCode)
{
return View(statusCode);
}
Run Code Online (Sandbox Code Playgroud)
这似乎捕获404
错误并显示正确的状态代码.
如果我在上面的if语句中更新我的代码以使用相同的操作,例如:
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error/{0}");
}
Run Code Online (Sandbox Code Playgroud)
返回的状态代码始终为0.
此外,当会发生什么400
,403
或其他任何发生?他们会被抓住吗?如果是这样,他们会在什么时候被抓住?
你可以告诉我,我很困惑,并希望有人为我提供一个处理所有不同状态代码的例子.
Mar*_*hes 23
听起来你混淆了未处理的异常(默认情况下,作为HTTP 500内部服务器错误返回到客户端)和由代表用户/客户端的无效操作(其中4xx HTTP)引起的正确处理的错误情况代码返回给用户).
只有前者与UseExceptionHandler调用有关 - 默认情况下它会捕获任何未处理的异常并将它们路由到你提供的任何内容(在你的情况下,一个视图,但它可以很容易地成为一段代码来检查将某些错误情况转换为HTTP 4xx返回代码的未处理异常 - 例如,将身份验证错误转换为HTTP 401响应).
只要尚未生成响应主体,UseStatusCodePagesWithReExecute将逐步生成400-599的状态代码.有问题的源代码显示了这是如何确定的.
在你的第二个代码块中,你使用了UseExceptionHandler - 我认为你应该有以下内容:
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
// Handle unhandled errors
app.UseExceptionHandler("/Home/Error");
// Display friendly error pages for any non-success case
// This will handle any situation where a status code is >= 400
// and < 600, so long as no response body has already been
// generated.
app.UseStatusCodePagesWithReExecute("/Error/{0}");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3772 次 |
最近记录: |