简体   繁体   English

ASP.NET MVC 5如何防止View显示为文本

[英]ASP.NET MVC 5 How to prevent View from displaying as text

I am new to MVC and am working on error handling and exceptions. 我是MVC的新手,正在研究错误处理和异常。 As you may or may not know, the implementation of handling HTTP errors through Views is outright clunky for the following reasons: 您可能知道也可能不知道,由于以下原因,通过Views处理HTTP错误的实现非常笨拙:

1.) The page status code is set to 200, which will result in the error page being indexed by a search engine and letting the user know that everything went OK, which is not true. 1.)页面状态代码设置为200,这将导致错误页面被搜索引擎索引,并让用户知道一切正常,这是不正确的。

2.) The URL of the error page changes, which I do not want. 2.)错误页面的URL更改了,我不需要。 Unfortunately, I cannot use ResponseRewrite with a View because it uses Server.Transfer under the hood, which means it looks for a file as opposed to a View. 不幸的是,我无法将ResponseRewrite与View一起使用,因为它在后台使用Server.Transfer,这意味着它查找的是文件而不是View。

I prefer to use a View for all application exception and HTTP error handling because the View maintains the site layout by calling _Layout.cshtml in the View startup. 我更喜欢将View用于所有应用程序异常和HTTP错误处理,因为View通过在View启动时调用_Layout.cshtml来维护网站布局。 So, after working on this for the past week, I think I found an implementation that allows me to use a View while addressing the two issues that I mentioned above (see Solution 1 by Starain Chen in the weblink below). 因此,在过去一周的研究中,我认为我找到了一个实现,使我可以使用View来解决上面提到的两个问题(请参阅下面的Weblink中的Starain Chen的解决方案1)。

My problem is this, for me the View is being displayed in all text. 我的问题是,对我而言,视图以所有文本显示。 Any ideas why this is happening, and more importantly, how to force the site to be rendered as opposed to being dumped out as text? 有什么想法为什么会发生这种情况,更重要的是,如何迫使网站呈现而不是作为文本转储?

https://forums.asp.net/t/1996026.aspx?How+to+keep+url+same+after+page+postback+with+error+in+MVC https://forums.asp.net/t/1996026.aspx?How+to+keep+url+same+after+page+postback+with+error+in+MVC

My code: 我的代码:

web.config (truncated) web.config(被截断)

<system.web>
    <customErrors mode="On" >      
    </customErrors>
</system.web>

<system.webServer>
    <modules>
         <remove name="FormsAuthentication" />
         <remove name="UrlRoutingModule-4.0" />
         <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" />     
    </modules>
</system.webServer> 

Global.asax Global.asax中

namespace WebApplication1
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        protected void Application_Error()
        {

            if (Context.IsCustomErrorEnabled)
                ShowError(Server.GetLastError());
        }

        private void ShowError(Exception exception)
        {
            var httpException = exception as HttpException ?? new HttpException(500, "Internal Server Error", exception);

            Response.Clear();
            var routeData = new RouteData();
            routeData.Values.Add("Controller", "Error");
            routeData.Values.Add("fromAppErrorEvent", true);
            routeData.Values.Add("ErrorMessage", httpException.Message);
            routeData.Values.Add("httpStatusCode", httpException.GetHttpCode());
            switch (httpException.GetHttpCode())
            {
                case 403:
                    routeData.Values.Add("action", "HttpError403");
                    break;
                case 404:
                    routeData.Values.Add("action", "HttpError404");
                    break;
                case 500:
                    routeData.Values.Add("action", "HttpError500");
                    break;
                default:
                    routeData.Values.Add("action", "GeneralError");
                    break;
            }

            Server.ClearError();

            IController controller = new Controllers.ErrorController();
            controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

        }
    }
}

ErrorController ErrorController

namespace WebApplication1.Controllers
{
    public class ErrorController : Controller
    {
        // GET: Error
        public ActionResult HttpError404()
        {
            ViewBag.errormessage = this.RouteData.Values["ErrorMessage"];
            ViewBag.status = this.RouteData.Values["httpStatusCode"];
            Response.StatusCode = Convert.ToInt32(this.RouteData.Values["httpStatusCode"]);
            Response.TrySkipIisCustomErrors = true;
            return View();
        }
    }
}

HttpError404.cshtml View HttpError404.cshtml视图

@{
    ViewBag.Title = "HttpError404";
}

@*<h2>HttpError404</h2>
ErrorMessge: @ViewBag.errormessage
<br />
Status: @ViewBag.status*@

Problem is caused by the project being open in Visual Studio 2013, oddly enough. 问题是由项目在Visual Studio 2013中打开引起的,这很奇怪。 Close the project and the View renders correctly in Firefox and even Chrome. 关闭项目,然后在Firefox和Chrome中正确显示View。 Open the project in VS2013 and Chrome and Firebox both go back to displaying text for the View. 在VS2013中打开项目,Chrome和Firebox都返回显示视图的文本。 IE must have some code awareness to render the project while VS2013 has the project open. VS2013打开项目时,IE必须具有一定的代码意识才能呈现项目。 Bizarre. 离奇。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM