gpt4 book ai didi

asp.net-core - 返回404页面,无需重定向

转载 作者:行者123 更新时间:2023-12-04 22:29:16 29 4
gpt4 key购买 nike

我试图使我的404正常工作,但无法弄清楚如何正确使用它。

最初,我在Statup Configure方法中设置以下内容:

app.UseMvc(routes =>
{
// routing here
});

app.Use((context, next) =>
{
context.Response.StatusCode = 404;
return next();
});

app.UseStatusCodePagesWithRedirects("/error/{0}");

哪个重定向到我显示错误的页面。但是,状态码为 302 > 200。我将 /error/{code} Action 设置为返回相关的状态码,所以现在我有了 302 > 404(由于302重定向),使其看上去好像 /error/404页面不存在(确实存在)。

我想做的是返回没有重定向的错误页面,以便尝试请求 /doesntexist将返回404并显示错误页面。

我尝试的另一件事是使用 app.UseStatusCodePagesWithReExecute("/error/{0}");,它确实返回404而不更改url,但仅显示空白页而不是我的错误页

最佳答案

在我的应用中,我这样做是这样的:

// custom 404 and error page - this preserves the status code (ie 404)
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");

我的HomeController具有此操作方法
public IActionResult Error(int statusCode)
{
if (statusCode == 404)
{
var statusFeature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
if (statusFeature != null)
{
log.LogWarning("handled 404 for url: {OriginalPath}", statusFeature.OriginalPath);
}

}
return View(statusCode);
}

我的看法是这样的:
@model int

@{
switch (Model)
{
case 400:
ViewData["Icon"] = "fa fa-ban text-danger";
ViewData["Title"] = "Bad Request";
ViewData["Description"] = "Your browser sent a request that this server could not understand.";
break;
case 401:
ViewData["Icon"] = "fa fa-ban text-danger";
ViewData["Title"] = "Unauthorized";
ViewData["Description"] = "Sorry, but the page requires authentication.";
break;
case 403:
ViewData["Icon"] = "fa fa-exclamation-circle text-danger";
ViewData["Title"] = "Forbidden";
ViewData["Description"] = "Sorry, but you don't have permission to access this page.";
break;
case 404:
ViewData["Icon"] = "fa fa-exclamation-circle text-danger";
ViewData["Title"] = "Page Not Found";
ViewData["Description"] = "Sorry, but the page you were looking for can't be found.";
break;
case 500:
default:
ViewData["Icon"] = "fa fa-exclamation-circle text-danger";
ViewData["Title"] = "Unexpected Error";
ViewData["Description"] = "Well, this is embarrassing. An error occurred while processing your request. Rest assured, this problem has been logged and hamsters have been released to fix the problem.";
break;
}
}

<div class="jumbotron text-center">
<header>
<h1><span aria-hidden="true" class="@ViewData["Icon"]"></span> @ViewData["Title"]</h1>
</header>
<p>@ViewData["Description"]</p>
<a class="btn btn-primary btn-lg" href="@Url.RouteUrl("/")"><span aria-hidden="true" class="fa fa-home"></span> Site Home</a>
</div>

正如@khellang所提到的,中间件的顺序很重要,这应该在app.UseMvc之前。

关于asp.net-core - 返回404页面,无需重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38996658/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com