【问题标题】:MVC View rendering as raw HTMLMVC 视图呈现为原始 HTML
【发布时间】:2015-10-05 19:29:09
【问题描述】:

我在 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 之类的内容时(这将导致它抛出 404,因为 999 是无效的房间 ID),它会重定向并呈现得很好,一切都按预期工作。

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

这是我的错误控制器

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 代码,然后将这个 sn-p 放在我的 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>

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

【问题讨论】:

  • 这个答案对自定义错误处理有很好的总结,应该很有帮助programmers.stackexchange.com/a/45197/88687
  • 这可能是我最终要走的路,因为这对 IIS 错误没有任何作用,但知道为什么会发生这种情况仍然很高兴。
  • 您能否发布您的视图代码,它呈现为原始 html。

标签: c# asp.net-mvc-5


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 2014-01-19
    • 2019-07-27
    相关资源
    最近更新 更多