MVC视图呈现为原始HTML
本文关键字:原始 HTML 视图 MVC | 更新日期: 2023-09-27 18:10:22
我在Global中使用了这段代码。一个捕获所有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));
}
}
}
目前我的应用程序有三个控制器,Users
, Rooms
和Home
当我输入像{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();
}
}
And my 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。配置错误处理,因为它更简单,我想。我从全局中删除了Application_Error代码。Asax文件,只是把这个片段在我的网页。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();
}