Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# mvc中的自定义错误处理不起作用_C#_Asp.net Mvc_Asp.net Mvc 3 - Fatal编程技术网

C# mvc中的自定义错误处理不起作用

C# mvc中的自定义错误处理不起作用,c#,asp.net-mvc,asp.net-mvc-3,C#,Asp.net Mvc,Asp.net Mvc 3,我正在处理控制器中的错误,并且我已经编写了[CustomErrorHandleAttribute],当我的操作中出现异常时,我该怎么做。即使我的代码中没有错误,它也会重定向到customerrorhandle并抛出错误。我无法找到它为什么这样做的错误 这是我的密码: namespace ExceptionHandlingInMVC.Controllers { [CustomHandleError] public class HomeController : Con

我正在处理控制器中的错误,并且我已经编写了
[CustomErrorHandleAttribute]
,当我的操作中出现异常时,我该怎么做。即使我的代码中没有错误,它也会重定向到customerrorhandle并抛出错误。我无法找到它为什么这样做的错误

这是我的密码:

    namespace ExceptionHandlingInMVC.Controllers
    {
    [CustomHandleError]
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public object Index()
        {
            try
            {
                ViewData["Title"] = "Home Page";
                ViewData["Message"] = "Current time is:" + DateTime.Now.ToLongTimeString();
                var x = 10;
                var y = 10;
                var result = x / y;
                ViewData["Result"] = result;
                return View();
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        [CustomHandleError]
        public object About()
        {
            ViewData["Title"] = "About Page";
            return View();
        }
    }

    public class ErrorPresentation
    {
        public String ErrorMessage { get; set; }
        public Exception TheException { get; set; }
        public Boolean ShowMessage { get; set; }
        public Boolean ShowLink { get; set; }


    }

  }
我写的CustomHandleErrorAttribute:

    namespace ExceptionHandlingInMVC
   {

    /// <summary>
    /// This attribute (AOP) filter is used to override the Error handling and make sure that all erros are recorded in the event logs, so that they can in turn be picked up by 
    /// our SIEM tool  so that we a) stop customers seing a bad error message and b) we are capturing all the events that happen and c) improives security for 
    /// by preventing a hacker from seing s=details of how our application is put together
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class CustomHandleErrorAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// This event is called when the action is called i.e. an error has just occured
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            try
            {
                // Bail if we can't do anything; app will crash.
                if (filterContext == null)
                    return;

                // since we're handling this, log to ELMAH(Error logging modules and handler)
                var ex = filterContext.Exception ?? new Exception("No further information exists.");
                WriteToEventLog(ex);

                filterContext.ExceptionHandled = true;
                var data = new ErrorPresentation
                {
                    ErrorMessage = HttpUtility.HtmlEncode(ex.Message),
                    TheException = ex,
                    ShowMessage = filterContext.Exception != null,
                    ShowLink = false
                };

                filterContext.Result = new ViewResult
                {
                    ViewName = "~/Views/Home/ErrorPage.aspx"
                };
            }
            catch (Exception exception)
            {

                throw;
            }

        }

        /// <summary>
        /// This method writes the exception to the event log we have specified in the web.config or the app.config
        /// </summary>
        /// <param name="exception"></param>
        public void WriteToEventLog(Exception exception)
        {
            // pick up which machine we are on, this will already be set for all websites
            var machineName = ConfigurationManager.AppSettings["MachineName"];

            // PIck up the eventlog we are going to write to
            var eventLogName = ConfigurationManager.AppSettings["EventLogName"];

            EventLog.WriteEntry("abc", exception.Message, EventLogEntryType.Error);

        }
    }
}
MVC中的命名空间异常处理 { /// ///此属性(AOP)筛选器用于覆盖错误处理,并确保所有错误都记录在事件日志中,以便由 ///我们的SIEM工具使我们a)阻止客户发出错误消息,b)捕获所有发生的事件,c)提高安全性 ///通过防止黑客窃取我们的应用程序如何组合的详细信息 /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] 公共密封类CustomHandleErrorAttribute:ActionFilterAttribute { /// ///调用操作(即刚刚发生错误)时调用此事件 /// /// 公共覆盖无效OnActionExecuted(ActionExecutedContext筛选器上下文) { 尝试 { //如果我们什么都做不了就保释;应用程序会崩溃。 如果(filterContext==null) 返回; //因为我们正在处理这个问题,所以将日志记录到ELMAH(错误日志记录模块和处理程序) var ex=filterContext.Exception??新的异常(“不存在进一步的信息”); WriteToEventLog(ex); filterContext.ExceptionHandled=true; var数据=新的错误表示 { ErrorMessage=HttpUtility.HtmlEncode(例如Message), TheException=ex, ShowMessage=filterContext.Exception!=null, ShowLink=false }; filterContext.Result=新的ViewResult { ViewName=“~/Views/Home/ErrorPage.aspx” }; } 捕获(异常) { 投掷; } } /// ///此方法将异常写入我们在web.config或app.config中指定的事件日志 /// /// 公共无效WriteToEventLog(异常) { //拿起我们正在使用的机器,这将为所有网站设置 var machineName=ConfigurationManager.AppSettings[“machineName”]; //拿起我们将要写入的事件日志 var eventLogName=ConfigurationManager.AppSettings[“eventLogName”]; WriteEntry(“abc”,exception.Message,EventLogEntryType.Error); } } } 试试这个:

public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        try
        {
            // Bail if we can't do anything; app will crash.
            if (filterContext == null)
                return;

            // since we're handling this, log to ELMAH(Error logging modules and handler)
            if (filterContext.Exception == null || filterContext.ExceptionHandled)
            {
                var ex = filterContext.Exception ?? new Exception("No further information exists.");
                this.WriteToEventLog(ex);
                return;
            };

            filterContext.ExceptionHandled = true;
            var data = new ErrorPresentation
            {
                ErrorMessage = HttpUtility.HtmlEncode(ex.Message),
                TheException = ex,
                ShowMessage = filterContext.Exception != null,
                ShowLink = false
            };

            filterContext.Result = new ViewResult
            {
                ViewName = "~/Views/Home/ErrorPage.aspx"
            };
        }
        catch (Exception exception)
        {

            throw;
        }

    }
如果没有exeption,则需要返回,因为该属性每次都会激发,而不仅仅是在出现错误时

更新: 我建议您在global.asax中编写以下代码:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CustomErrorHandle());
    }
对所有的行动都采取这种态度。因此,您不需要为任何操作写入属性。

尝试以下操作:

public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        try
        {
            // Bail if we can't do anything; app will crash.
            if (filterContext == null)
                return;

            // since we're handling this, log to ELMAH(Error logging modules and handler)
            if (filterContext.Exception == null || filterContext.ExceptionHandled)
            {
                var ex = filterContext.Exception ?? new Exception("No further information exists.");
                this.WriteToEventLog(ex);
                return;
            };

            filterContext.ExceptionHandled = true;
            var data = new ErrorPresentation
            {
                ErrorMessage = HttpUtility.HtmlEncode(ex.Message),
                TheException = ex,
                ShowMessage = filterContext.Exception != null,
                ShowLink = false
            };

            filterContext.Result = new ViewResult
            {
                ViewName = "~/Views/Home/ErrorPage.aspx"
            };
        }
        catch (Exception exception)
        {

            throw;
        }

    }
如果没有exeption,则需要返回,因为该属性每次都会激发,而不仅仅是在出现错误时

更新: 我建议您在global.asax中编写以下代码:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CustomErrorHandle());
    }

对所有的行动都采取这种态度。因此,您不需要将属性写入任何操作。

仅当出现错误且我正在写入事件日志时,应触发事件:

在my global.asax中,我添加了以下代码:

    /// <summary>
    /// Managing errors from a single location 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void Application_Error(object sender, EventArgs e)
    {
        // 1. Get the last error raised
        var error = Server.GetLastError();

        //2. Get the error code to respond with
        var code = (error is HttpException) ? (error as HttpException).GetHttpCode() : 500;

        //3.. Log the error ( I am ignoring 404 error)
        if (code != 404)
        {
            // Write error details to eventlog
            WriteToEventLog(error);
        }

        //4. Clear the response stream
        Response.Clear();

        //5. Clear the server error
        Server.ClearError();

        //6. Render the Error handling controller without a redirect
        string path = Request.Path;
        Context.RewritePath(string.Format("~/Home/Error",code),false);
        IHttpHandler httpHandler = new MvcHttpHandler();
        httpHandler.ProcessRequest(Context);
        Context.RewritePath(path,false);
    }

     /// <summary>
    /// This method writes the exception to the event log we have specified in the web.config or the app.config
    /// </summary>
    /// <param name="exception"></param>
    public void WriteToEventLog(Exception exception)
    {
        EventLog.WriteEntry("abc", exception.Message, EventLogEntryType.Error);
    }
//
///从单个位置管理错误
/// 
/// 
/// 
无效应用程序错误(对象发送方,事件参数e)
{
//1.获取引发的最后一个错误
var error=Server.GetLastError();
//2.获取要响应的错误代码
var代码=(错误为HttpException)?(错误为HttpException)。GetHttpCode():500;
//3.记录错误(我忽略404错误)
如果(代码!=404)
{
//将错误详细信息写入事件日志
WriteToEventLog(错误);
}
//4.清除响应流
Response.Clear();
//5.清除服务器错误
ClearError();
//6.在不重定向的情况下呈现错误处理控制器
字符串路径=Request.path;
重写路径(string.Format(“~/Home/Error”,code),false);
IHttpHandler httpHandler=新的MVHttpHandler();
ProcessRequest(上下文);
重写路径(路径,false);
}
/// 
///此方法将异常写入我们在web.config或app.config中指定的事件日志
/// 
/// 
公共无效WriteToEventLog(异常)
{
WriteEntry(“abc”,exception.Message,EventLogEntryType.Error);
}

仅当出现错误且我正在写入事件日志时,应触发事件:

在my global.asax中,我添加了以下代码:

    /// <summary>
    /// Managing errors from a single location 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void Application_Error(object sender, EventArgs e)
    {
        // 1. Get the last error raised
        var error = Server.GetLastError();

        //2. Get the error code to respond with
        var code = (error is HttpException) ? (error as HttpException).GetHttpCode() : 500;

        //3.. Log the error ( I am ignoring 404 error)
        if (code != 404)
        {
            // Write error details to eventlog
            WriteToEventLog(error);
        }

        //4. Clear the response stream
        Response.Clear();

        //5. Clear the server error
        Server.ClearError();

        //6. Render the Error handling controller without a redirect
        string path = Request.Path;
        Context.RewritePath(string.Format("~/Home/Error",code),false);
        IHttpHandler httpHandler = new MvcHttpHandler();
        httpHandler.ProcessRequest(Context);
        Context.RewritePath(path,false);
    }

     /// <summary>
    /// This method writes the exception to the event log we have specified in the web.config or the app.config
    /// </summary>
    /// <param name="exception"></param>
    public void WriteToEventLog(Exception exception)
    {
        EventLog.WriteEntry("abc", exception.Message, EventLogEntryType.Error);
    }
//
///从单个位置管理错误
/// 
/// 
/// 
无效应用程序错误(对象发送方,事件参数e)
{
//1.获取引发的最后一个错误
var error=Server.GetLastError();
//2.获取要响应的错误代码
var代码=(错误为HttpException)?(错误为HttpException)。GetHttpCode():500;
//3.记录错误(我忽略404错误)
如果(代码!=404)
{
//将错误详细信息写入事件日志
WriteToEventLog(错误);
}
//4.清除响应流
Response.Clear();
//5.清除服务器错误
ClearError();
//6.在不重定向的情况下呈现错误处理控制器
字符串路径=Request.path;
重写路径(string.Format(“~/Home/Error”),