MVC视图呈现为原始HTML

6
我在全局文件Global.asax中使用这段代码来捕获所有404错误并将它们重定向到自定义控制器/视图。
    protected void Application_Error(object sender, EventArgs e) {
        Exception exception = Server.GetLastError();

        Response.Clear();
        HttpException httpException = exception as HttpException;
        if (httpException != null) {
            if (httpException.GetHttpCode() == 404) {
                RouteData routeData = new RouteData();
                routeData.Values.Add("controller", "Error");
                routeData.Values.Add("action", "Index");

                Server.ClearError();

                IController errorController = new webbage.chat.Controllers.ErrorController();
                Response.StatusCode = 404;
                errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
            }
        }
    }

我目前有三个控制器,分别为UsersRoomsHome,这些都与我的应用程序相关。
当我输入像{localhost}/rooms/999这样的内容时(因为999是无效的房间ID,所以会导致它抛出404错误),重定向和呈现都很好,一切正常。
然而,如果我输入一个无效的控制器名称,例如{localhost}/test,它会将其重定向到视图,但在呈现时它只是普通文本的HTML。有人能指出这是为什么吗?
以下是我的ErrorController:
public class ErrorController : Controller {
    public ActionResult Index() {
        return View();
    }

    public ActionResult NotFound() {
        return View();
    }

    public ActionResult Forbidden() {
        return View();
    }
}

我的观点是:
@{
    ViewBag.Title = "Error";
}

<div class="container">
    <h1 class="text-pumpkin">Ruh-roh</h1>
    <h3 class="text-wet-asphalt">The page you're looking for isn't here.</h3>
</div>

编辑

我最终选择只使用web.config错误处理,因为它更加简单。我从Global.asax文件中删除了Application_Error代码,并在web.confg文件中添加了以下片段:

  <system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">      
      <remove statusCode="403"/>
      <remove statusCode="404"/>
      <remove statusCode="500"/>
      <error statusCode="403" responseMode="ExecuteURL" path="/Error/Forbidden" />
      <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
      <error statusCode="500" responseMode="ExecuteURL" path="/Error" />
    </httpErrors>
  </system.webServer>

不过,我仍然想知道为什么会发生这种情况。


这个答案对于自定义错误处理有非常好的总结,应该非常有帮助。http://programmers.stackexchange.com/a/45197/88687 - Lanorkin
那可能是我最终采取的路线,因为这对IIS错误没有任何作用,但知道为什么会发生这种情况仍然很好。 - Ben Black
你能否发布你的视图代码,它会呈现为原始HTML。 - Govind
1个回答

7
您可以尝试在操作中明确设置ContentType:
public ActionResult NotFound() {
    // HACK: fix rendering raw HTML when a controller can't be found 
    Response.ContentType = "text/html";
    return View();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接