在404上的其他控制器中执行操作

时间:2013-09-16 06:36:08

标签: asp.net-mvc asp.net-mvc-3

我正在尝试返回驻留在“Error”控件中的动作“PageNotFound”。

public class BaseController : Controller
{
 public BaseController()
 {
 }

 public BaseController(IContentRepository contentRep, ILocalizedRepository localRep)
 {
    this._localRep = localRep;
    this._contentRep = contentRep;
 }

 protected new HttpNotFoundResult HttpNotFound(string statusDescription = null)
 {
    return new HttpNotFoundResult(statusDescription);
 }

protected HttpUnauthorizedResult HttpUnauthorized(string statusDescription = null)
{
    return new HttpUnauthorizedResult(statusDescription);
}

 protected class HttpNotFoundResult : HttpStatusCodeResult
 {
    public HttpNotFoundResult() : this(null) { }

    public HttpNotFoundResult(string statusDescription) : base(404, statusDescription) { }
 }

 protected class HttpUnauthorizedResult : HttpStatusCodeResult
 {
    public HttpUnauthorizedResult(string statusDescription) : base(401, statusDescription) { }
 }

 protected class HttpStatusCodeResult : ViewResult
 {
    public int StatusCode { get; private set; }
    public string StatusDescription { get; private set; }

    public HttpStatusCodeResult(int statusCode) : this(statusCode, null) { }

    public HttpStatusCodeResult(int statusCode, string statusDescription)
    {
        this.StatusCode = statusCode;
        this.StatusDescription = statusDescription;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        context.HttpContext.Response.StatusCode = this.StatusCode;
        if (this.StatusDescription != null)
        {
            context.HttpContext.Response.StatusDescription = this.StatusDescription;
        }

        this.ViewName = "PageNotFound";  // CONTROLLER MISSING
        this.ViewBag.Message = context.HttpContext.Response.StatusDescription;
        base.ExecuteResult(context);
     }
 }

如何修改它以便在“错误” - 控制器中返回“PageNotFound”操作?

3 个答案:

答案 0 :(得分:2)

ViewResult应该直接呈现视图(可选地传递模型和布局)。这个过程中没有涉及控制器。

如果您想要通过控制器,则需要执行重定向,即使用RedirectToRouteResult代替ViewResult

在您的示例中,您直接在其他控制器中使用此自定义ViewResult。这将是将呈现错误视图的控​​制器。

答案 1 :(得分:1)

我不明白为什么要进行重定向。我会回复404

return HttpStatusCode(404);

然后使用此处描述的方法:ASP.NET MVC 404 Error Handling来呈现正确的视图。好处:您的网址仍然相同,更容易进行错误处理和浏览器历史记录。

答案 2 :(得分:0)

你试过吗

return RedirectToAction("PageNotFound", "ControllerName");