NotFound() 似乎没有按预期工作

NotFound() doesn't seem to work as expected

我是 ASP.NET 核心的新手,所以希望您能多多包涵。这类似于 this unanswered question.

当我测试一个全新的 C# MVC 项目时,我输入了错误的 URL,没有任何信息。只是一个空白页。

为了解决这个问题,我调整了 startup.cs 添加 UseStatusCodePagesWithReExecute() 到 return 静态 404.html 页面。这行得通。

到目前为止,还不错。

现在,我正在编写基本的登录逻辑。出于测试目的,我在缺少 post 参数时调用 return NotFound();。这没有 return 任何东西。我知道 404 不是正确的响应,但我在生成的代码中看到 NotFound();,我认为这就是 return 空白页,所以我想在继续之前解决这个问题。

app.UseDeveloperException(); 似乎不是为此而调用的。我不确定如何测试它。

有没有办法覆盖 NotFound(); 行为以某种方式获得 404.html?

这是the Tutorial我用来设置我的项目。

编辑: 根据 Alexander Powolozki 的评论,我将 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");
        }
    }
}

当由于缺少静态内容或控制器等资源的路由而无法处理请求时,将调用带有 404.html 的第一个选项,在这种情况下,将返回预配置的 404.html。在第二种情况下,路由成功,所有剩余的处理都由逻辑完成,例如确定和调用的控制器,因此您可以重定向到您创建的 404.html.

在对该问题进行更多研究后,我找到了一种不使用 Alexander Powolozki 所建议的重定向的方法。

我创建了 Utilities class 到 return 404 代码和 404.html.

在 HomeController 中,我有 StatusCode IActionResult。

// This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
public IActionResult StatusCode(int? code)
{
    // Call the static method
    return Utilities.StatusCode(code: code.Value, this.HttpContext);
}

在模型中,我添加了一个 Utilities.cs。

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.IO;

namespace MediaMgt.Models
{
    public static class Utilities
    {
        public static IActionResult StatusCode(int code, HttpContext httpContext)
        {
            // here is the trick
            httpContext.Response.StatusCode = code;

            //return a static file.
            try
            {
                return new VirtualFileResult("~/" + code + ".html", "text/html");
            }
            catch (FileNotFoundException)
            {
                httpContext.Response.StatusCode = 404;
                return new VirtualFileResult("~/404.html", "text/html");
            }
        }
    }
}

这样做而不是使用 Redirect 方法的原因是为了避免使用 302 往返客户端。此方法 returns 404 错误代码和标准 404.html.

您可以从这里轻松添加更多功能。