如何覆盖Web.Config中的HttpErrors部分 - ASP.NET MVC3

时间:2011-05-17 15:57:34

标签: asp.net-mvc-3 iis-7 web-config

我正在尝试根据此问题的答案添加custon 404页面

ASP.NET MVC 404 handling and IIS7 <httpErrors>

添加

<httpErrors existingResponse="PassThrough" />

在我的Web.Config文件中的<system.webServer>标记下。

但我收到了以下错误

Module: CustomErrorModule 
Notification: SendResponse 
Handler: System.Web.Mvc.MvcHandler 
Error Code: 0x80070021 
Config Error: This configuration section cannot be used at this path. 
              This happens when the section is locked at a parent level. 
              Locking is either by default (overrideModeDefault="Deny"), 
              or set explicitly by a location tag with overrideMode="Deny" 
              or the legacy allowOverride="false".  


 Config Source
  153:       <httpErrors existingResponse="PassThrough" />
  154:   </system.webServer>

我还尝试根据http://learn.iis.net/page.aspx/145/how-to-use-locking-in-iis-70-configuration(任务2)

覆盖锁定

在Web.config中添加位置标记

如下

<configuration>
....
....

  <location  allowOverride="true">
        <system.webServer>
            <httpErrors existingResponse="PassThrough" />
        </system.webServer>
  </location>
</configuration>

但我收到同样的错误。

我应该如何在Web.config中配置httpErrors元素以使其正常工作

我正在使用IIS 7,VS 2010,ASP.NET MVC3

更新

我能够摆脱锁定的错误

如果我修改applicationHost.config文件并更改

<section name="httpErrors" overrideModeDefault="Deny" />

<section name="httpErrors" overrideModeDefault="Allow" />

但理想情况下我不想更改applicationHost.config文件并希望从Web.config文件覆盖它

1 个答案:

答案 0 :(得分:3)

如果您有兴趣,可以从Global.asax.cs创建自定义错误处理:

protected void Application_Error()
        {

                var exc = Server.GetLastError();
                var httpExc = exc as HttpException;
                Response.Clear();
                Server.ClearError();
                var routeData = new RouteData();
                routeData.Values["controller"] = "Error";
                routeData.Values["action"] = "General";
                routeData.Values["exception"] = exc;
                Response.StatusCode = 500;
                if (httpExc != null)
                {
                    Response.StatusCode = httpExc.GetHttpCode();
                    routeData.Values["action"] = "Http404";
                    routeData.Values["exception"] = httpExc;
                }
                Response.TrySkipIisCustomErrors = true;
                IController errorsController = new WWS_Website.Controllers.ErrorController();
                var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
                errorsController.Execute(rc);

        }

控制器:

public ActionResult General(Exception exception)
{
  return View(exception);
}

public ActionResult Http404(Exception exception)
{
  return View(exception);
}

每个错误都可以有不同的视图。您也可以通过此控制器方法向您的网站管理员电子邮件帐户发送电子邮件 - 非常方便。