c# - MVC View 呈现为原始 HTML

标签 c# asp.net-mvc-5

我在我的 Global.asax 文件中使用这段代码来捕获所有 404 错误并将它们重定向到自定义 Controller / View 。

    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));
            }
        }
    }

目前我的应用程序有三个 Controller ,UsersRoomsHome

当我输入类似 {localhost}/rooms/999 的内容时(这会导致它抛出 404,因为 999 是一个无效的房间 ID),它会重定向并呈现得很好,一切正常正如预期的那样。

但是,如果我输入一个无效的 Controller 名称,如 {localhost}/test 它会像它应该的那样将它重定向到 View ,但是当它呈现时它只是纯文本的 HTML。有人可以指出为什么要这样做吗?

这是我的错误 Controller

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>

不过,我仍然很想知道为什么会这样。

最佳答案

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

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

关于c# - MVC View 呈现为原始 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437635/

相关文章:

c# - 从url获取正确的下载文件大小

c# - 在 Unity3d 中导入数学时出错

c# - 为什么 MouseMove 事件发生在 MouseUp 事件之后?

asp.net-mvc - 自定义 MVC razor View 引擎的间歇性 View 路径问题

c# - 将 Identity 2.0 函数移动到存储库类

c# - 如何将 Url.Action 与列表参数一起使用?

c# - 在 winrt 中遵循 SOLID 原则的同时捕获异常

C# .NET - 存储一些非常小规模的持久信息的方法?

asp.net-mvc - MVC5 [Authorize] 重定向到默认路由而不是属性路由

css - Bootstrap-在表单中选择宽度