【发布时间】:2020-07-28 09:28:57
【问题描述】:
这些天我正在处理 404 Not Found by Asp.Net Core。
我们知道,有几种方法可以实现这一点:app.UseStatusCodePagesWithRedirects/app.UseStatusCodePagesWithReExecute/app.UseStatusCodePages。
我必须选择 app.UseStatusCodePages,因为我需要通过 URL 对页面进行本地化。
例如:
https://www.microsoft.com/en-us/microsoft-365/
URL 中的“en-us”仅用于决定页面的语言。
这是我在 startup.cs 中的代码
app.UseStatusCodePages(async context =>
{
string currentCulture = "";
if (context.HttpContext.Request.Path.Value.Split('/').Length < 2)
{
currentCulture = "en";
}
else
{
string LanguageGet = context.HttpContext.Request.Path.Value.Split('/')[1];
currentCulture = SupportedCultures.Find(X => X.Name == LanguageGet) == null ? "en" : SupportedCultures.Find(X => X.Name == LanguageGet).Name;
}
var redirectPath = "/" + currentCulture + "/Error/" + context.HttpContext.Response.StatusCode;
context.HttpContext.Response.Redirect(redirectPath);
});
现在可以了。
但是,在我输入一个不存在的 URL(localhost:4387/en/123.html) 之后。标头在 Chrome DevTools 网络中显示 302 状态代码,但不是 404 状态代码。
好吧,当我输入不存在的 URL(https://www.microsoft.com/en-us/123.html) 时,标题在 Chrome DevTools 的网络中显示正确的 404 状态码。这正是我需要的正确状态码。
我在 Google 上搜索过这个。有人说我应该在控制器中添加一个ProducesResponseType,就像这样:
public class OthersController : Controller
{
[Route("{culture=en}/Error/{code:int}")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult Error(int code)
{
return View(code);
}
}
好吧,它没有任何作用。由于 SEO,我想解决这个问题。
这里是onedrive中这个示例项目的所有源代码:https://1drv.ms/u/s!AtcqjirAlaGYiuUyWqy8gzpgPF9U1Q?e=8WTYln
我该如何解决这个问题?谢谢。
【问题讨论】:
-
如果输入现有页面地址,本地化输入为
en,是显示为302错误还是404错误? -
@YongqingYu 404错误。
标签: asp.net-core .net-core asp.net-core-mvc