如果给出了路由:
{FeedName}/{ItemPermalink}
例如: /Blog/Hello-World
如果项不存在,我想返回一个404。在ASP.NET MVC中做这件事的正确方法是什么?
发布于 2009-02-01 00:26:57
直接说(牛仔编码;-)),我建议这样做:
控制器:
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是如何实现的,因为我不知道这种方法是否遗漏了什么(几乎看起来太简单了)。
我刚才确实用反射器看了一下HttpUnauthorizedResult。似乎他们将响应的StatusCode设置为0x191 (401)。虽然这适用于401,但使用404作为新值,我在Firefox中似乎只得到一个空白页面。但Internet Explorer显示的是默认的404 (不是ASP.NET版本)。使用webdeveloper工具栏,我检查了FF中的头文件,它确实显示了404 Not Found响应。可能是我在FF中配置错误的原因。
这就是说,我认为Jeff的方法是KISS的一个很好的例子。如果您不需要这个示例中的冗长,那么他的方法也可以很好地工作。
发布于 2009-02-01 00:39:34
我们这样做;这段代码可以在BaseController
中找到
/// <summary>
/// returns our standard page not found view
/// </summary>
protected ViewResult PageNotFound()
{
Response.StatusCode = 404;
return View("PageNotFound");
}
名字是这样的
public ActionResult ShowUserDetails(int? id)
{
// make sure we have a valid ID
if (!id.HasValue) return PageNotFound();
发布于 2009-02-01 00:04:27
throw new HttpException(404, "Are you sure you're in the right place?");
https://stackoverflow.com/questions/499817
复制相似问题