MVC将渲染视为原始HTML

Ben*_*ack 6 c# asp.net-mvc-5

我在我的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));
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我现在有三个控制器用于我的应用程序Users,Rooms和Home

当我输入类似的东西{localhost}/rooms/999(这会导致它抛出404,因为999是一个无效的房间ID),它重定向和呈现就好了,一切都按预期工作.

但是,如果我输入一个无效的控制器名称,{localhost}/test它会将它重定向到它应该的视图,但是当它呈现它只是HTML作为纯文本.有人能指出为什么会这样做吗?

这是我的ErrorController

public class ErrorController : Controller {
    public ActionResult Index() {
        return View();
    }

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

    public ActionResult Forbidden() {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的观点是:

@{
    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>
Run Code Online (Sandbox Code Playgroud)

编辑

我最后只使用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>
Run Code Online (Sandbox Code Playgroud)

我仍然很想知道为什么会这样.

ajb*_*ven 7

您可以尝试在操作中显式设置ContentType:

public ActionResult NotFound() {
    // HACK: fix rendering raw HTML when a controller can't be found 
    Response.ContentType = "text/html";
    return View();
}
Run Code Online (Sandbox Code Playgroud)