简体   繁体   English

使用MVC4进行自定义错误处理

[英]Custom Error Handling with MVC4

I have a relatively untouched MVC4 project with the following in my Web.Release.config: 我在Web.Release.config中有一个相对简单的MVC4项目,其中包含以下内容:

<system.web>
<customErrors mode="On" defaultRedirect="~/Error">
  <error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
</system.web>

It's not working though - I get normal error pages when in Release mode. 不过,它无法正常工作-在“发布”模式下,我得到正常的错误页面。

If I place that code in my Web.Config, it works as expected. 如果将代码放在Web.Config中,它将按预期工作。 I only want this applied when in Release though. 我只希望在发布时应用此功能。

I also tried this in web.release.config: 我也在web.release.config中尝试了这个:

  <system.web>
    <customErrors mode="On" defaultRedirect="~/Error" xdt:Transform="Replace">
       <error redirect="~/Error/NotFound" statusCode="404" />
    </customErrors>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
  </system.web>

To no avail. 无济于事。

Why would this be happening? 为什么会这样呢?

UPDATE: If I use the following in my global.asax: 更新:如果我在global.asax中使用以下内容:

    void Application_Error(object sender, EventArgs e)
        {

#if DEBUG
#else
            Response.Redirect("/Error");
#endif
            return;
        }

I get the desired behavior. 我得到期望的行为。 I feel like I should be able to use the web.config settings only though... so I'd like to leave this open. 我觉得我虽然应该只能使用web.config设置,所以我想保持打开状态。

The problem is you're not publishing. 问题是您没有发布。 The web.release.config file is only transformed during publish as far as I know. 据我所知,web.release.config文件仅在发布期间进行转换。 If you're just building and running locally that file won't be used. 如果您只是在本地构建和运行,则不会使用该文件。

Also in your Application_Error you should get the status code for the error. 同样在Application_Error您应该获得错误的状态代码。 Something like 就像是

var exception = Server.GetLastError();

var httpException = exception as HttpException;

if (httpException != null) 
{
    if (httpException.GetHttpCode() == 404)
        RedirectToMyNotFoundPage();

} 

Otherwise you will basically just handle all errors, which may or may not be what you want to do. 否则,您基本上只会处理所有错误,这可能是您可能要做的,也可能不是。

If you want to handle MvcErrors, and get the controller/action that the exception occured in, you should look into Filters. 如果要处理MvcErrors,并获取发生异常的控制器/操作,则应查看“过滤器”。

Here's a good article on error filtering if that's what you're going for. 如果您要这样做,这是一篇有关错误过滤的好文章。

http://blogs.msdn.com/b/gduthie/archive/2011/03/17/get-to-know-action-filters-in-asp-net-mvc-3-using-handleerror.aspx http://blogs.msdn.com/b/gduthie/archive/2011/03/17/get-to-know-action-filters-in-asp-net-mvc-3-using-handleerror.aspx

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

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