0

我正在尝试返回驻留在我的“错误”控制器中的操作“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”操作?

4

3 回答 3

2

AViewResult应该直接渲染视图(可选地传递模型和布局)。此过程不涉及任何控制器。

如果你想通过一个控制器,你需要执行重定向,即使用RedirectToRouteResult而不是ViewResult.

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

于 2013-09-16T06:39:02.267 回答
1

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

return HttpStatusCode(404);

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

于 2013-09-16T09:08:32.187 回答
0

你有没有尝试过

return RedirectToAction("PageNotFound", "ControllerName");
于 2013-09-16T06:40:01.777 回答