【发布时间】:2020-09-15 16:07:09
【问题描述】:
我是 ASP.NET 核心的新手,所以我希望你能在这个问题上多多包涵。这类似于this unanswered question。
当我测试一个全新的 C# MVC 项目时,我输入了错误的 URL,没有任何信息。只是一个空白页。
为了解决这个问题,我调整了startup.cs 添加UseStatusCodePagesWithReExecute() 以返回静态404.html 页面。这行得通。
到目前为止,一切都很好。
现在,我正在编写一个基本的登录逻辑。出于测试目的,当缺少 post 参数时,我会调用 return NotFound();。这不会返回任何东西。我知道 404 不是正确的响应,但我在生成的代码中看到了NotFound();,我认为这就是返回空白页的原因,所以我想在继续之前解决这个问题。
似乎没有为此调用app.UseDeveloperException();。我不确定如何测试。
有没有办法覆盖 NotFound(); 行为以某种方式获得 404.html?
这是the Tutorial我用来设置我的项目。
编辑:
基于 Alexander Powolozki 的 cmets,我已将 NotFound(); 替换为 Redirect("~/404.html");。这行得通。
// Wherever you want to return your standard 404 page
return Redirect("Home/StatusCode?code=404");
public class HomeController : Controller
{
// This method allows for other status codes as well
public IActionResult StatusCode(int? code)
{
// This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
if (code.HasValue)
{
// here is the trick
this.HttpContext.Response.StatusCode = code.Value;
}
//return a static file.
try
{
return File("~/" + code + ".html", "text/html");
}
catch (FileNotFoundException)
{
return Redirect("Home/StatusCode?code=404");
}
}
}
【问题讨论】:
-
AFAIK 404.html 的第一个选项在由于错过了到静态内容或控制器等资源的路由而无法处理时调用,在这种情况下会返回预配置的 404.html。在第二种情况下,路由成功,所有剩余的处理都由逻辑完成,例如确定和调用的控制器,因此由您决定重定向到您创建的 404.html。
-
@AlexanderPowolozki 第一个案例解决了。对于第二种情况,您是说“不要使用 NotFound()”,还是我必须创建一个 NotFoundController 类?
-
对于第二种情况,您必须重定向到您的自定义 404.html。
-
我的回答更好有两个原因。 1.减少往返次数。您只发送 404 消息,而不是发送 302 和 404 消息。 2.您的答案中没有代码。我在我的问题和回答中都归咎于你。我希望你现在明白我为什么接受我自己的答案。
-
@AlexanderPowolozki 干杯。
标签: c# asp.net-mvc asp.net-core asp.net-core-mvc http-status-code-404