我在我的 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 ,Users
、Rooms
和 Home
当我输入类似 {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/