asp.net - 从 ASP.NET MVC 操作发送 HTTP 404 响应的正确方法是什么?

标签 asp.net asp.net-mvc http-status-code-404

如果给定路线:

{FeedName}/{ItemPermalink}

例如:/Blog/Hello-World

如果该项目不存在,我想返回 404。在 ASP.NET MVC 中执行此操作的正确方法是什么?

最佳答案

从臀部射击(牛仔编码;-)),我建议这样的事情:

Controller :

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return new HttpNotFoundResult("This doesn't exist");
    }
}
<小时/>

HttpNotFoundResult:

using System;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace YourNamespaceHere
{
    /// <summary>An implementation of <see cref="ActionResult" /> that throws an <see cref="HttpException" />.</summary>
    public class HttpNotFoundResult : ActionResult
    {
        /// <summary>Initializes a new instance of <see cref="HttpNotFoundResult" /> with the specified <paramref name="message"/>.</summary>
        /// <param name="message"></param>
        public HttpNotFoundResult(String message)
        {
            this.Message = message;
        }

        /// <summary>Initializes a new instance of <see cref="HttpNotFoundResult" /> with an empty message.</summary>
        public HttpNotFoundResult()
            : this(String.Empty) { }

        /// <summary>Gets or sets the message that will be passed to the thrown <see cref="HttpException" />.</summary>
        public String Message { get; set; }

        /// <summary>Overrides the base <see cref="ActionResult.ExecuteResult" /> functionality to throw an <see cref="HttpException" />.</summary>
        public override void ExecuteResult(ControllerContext context)
        {
            throw new HttpException((Int32)HttpStatusCode.NotFound, this.Message);
        }
    }
}
// By Erik van Brakel, with edits from Daniel Schaffer :)

使用这种方法您就可以遵守框架标准。那里已经有一个 HttpUnauthorizedResult,所以这只会在稍后维护您的代码的另一个开发人员眼中扩展框架(您知道,知道您住在哪里的精神病患者)。

您可以使用 Reflector 来查看程序集,看看 HttpUnauthorizedResult 是如何实现的,因为我不知道这种方法是否遗漏了任何内容(看起来太简单了)。

<小时/>

我刚才确实使用了 Reflector 来查看 HttpUnauthorizedResult。似乎他们正在将响应上的 StatusCode 设置为 0x191 (401)。虽然这适用于 401,但使用 404 作为新值我似乎在 Firefox 中得到的只是一个空白页面。但 Internet Explorer 显示默认的 404(不是 ASP.NET 版本)。我使用 webdeveloper 工具栏检查了 FF 中的 header ,其中确实显示了 404 Not Found 响应。可能只是我在 FF 中配置错误。

<小时/>

话虽这么说,我认为 Jeff 的方法是 KISS 的一个很好的例子。如果您确实不需要此示例中的冗长内容,那么他​​的方法也可以很好地工作。

关于asp.net - 从 ASP.NET MVC 操作发送 HTTP 404 响应的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/499817/

相关文章:

asp.net - CSS Sprite 显示内联 block 在 IE 浏览器中显示不正确

asp.net 身份不记名 token 在 20 分钟后过期

asp.net - 向LINQ中向SQL生成的类添加新方法

css - asp.net MVC、Bootstrap 和 CSS。下拉列表问题

.net - ASP.NET MVC - IsAjaxRequest() 的实际含义是什么?

linux - 如何阻止 Debian Linux 在运行 apt-get update 时抛出错误

java - Azure spring应用程序部署,找不到 Controller 404

.net - 使用 ASP.NET AJAX 填充列表后更新 View 状态

jquery - 如何在 ASP.NET MVC 中将 flot 与 jQuery 结合使用?

php - 如何自定义404错误页面(ubuntu nginx)