수색…


단순 속성

using System;
using System.Web;
using System.Web.Mvc;

namespace Example.SDK.Filters
{
    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
    public sealed class CustomErrorHandlerFilter : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            // RouteDate is useful for retrieving info like controller, action or other route values
            string controllerName = filterContext.RouteData.Values["controller"].ToString();
            string actionName = filterContext.RouteData.Values["action"].ToString();

            string exception = filterContext.Exception.ToString(); // Full exception stack
            string message = filterContext.Exception.Message; // Message given by the exception

            // Log the exception within database
            LogExtensions.Insert(exception.ToString(), message, controllerName + "." + actionName);

            base.OnException(filterContext);
        }
    }
}

그런 다음 FilterConfig.cs 에서 설정하십시오.

filters.Add(new CustomErrorHandlerFilter());

맞춤 오류 페이지 반환

public ActionResult Details( string product)
{
   ....
    if (productNotFound) {
        // http://www.eidias.com/blog/2014/7/2/mvc-custom-error-pages
        Response.Clear();
        Response.TrySkipIisCustomErrors = true;
        Response.Write(product + " product not exists");
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        Response.End();
        return null;
    }

}

ASP.Net MVC에서 사용자 정의 ErrorLogger 만들기

1 단계 : DateWise에 따라 텍스트 파일에 오류를 작성하는 사용자 정의 오류 로깅 필터 작성.

public class ErrorLogger : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {

        string strLogText = "";
        Exception ex = filterContext.Exception;
        filterContext.ExceptionHandled = true;
        var objClass = filterContext;
        strLogText += "Message ---\n{0}" + ex.Message;

        if (ex.Source == ".Net SqlClient Data Provider")
        {
            strLogText += Environment.NewLine + "SqlClient Error ---\n{0}" + "Check Sql Error";
        }
        else if (ex.Source == "System.Web.Mvc")
        {
            strLogText += Environment.NewLine + ".Net Error ---\n{0}" + "Check MVC Code For Error";
        }
        else if (filterContext.HttpContext.Request.IsAjaxRequest() == true)
        {
            strLogText += Environment.NewLine + ".Net Error ---\n{0}" + "Check MVC Ajax Code For Error";
        }
        strLogText += Environment.NewLine + "Source ---\n{0}" + ex.Source;
        strLogText += Environment.NewLine + "StackTrace ---\n{0}" + ex.StackTrace;
        strLogText += Environment.NewLine + "TargetSite ---\n{0}" + ex.TargetSite;
        if (ex.InnerException != null)
        {
            strLogText += Environment.NewLine + "Inner Exception is {0}" + ex.InnerException;//error prone
        }
        if (ex.HelpLink != null)
        {
            strLogText += Environment.NewLine + "HelpLink ---\n{0}" + ex.HelpLink;//error prone
        }

        StreamWriter log;

        string timestamp = DateTime.Now.ToString("d-MMMM-yyyy", new CultureInfo("en-GB"));

        string error_folder = ConfigurationManager.AppSettings["ErrorLogPath"].ToString();

        if (!System.IO.Directory.Exists(error_folder))
        {
            System.IO.Directory.CreateDirectory(error_folder);
        }

        if (!File.Exists(String.Format(@"{0}\Log_{1}.txt", error_folder, timestamp)))
        {
            log = new StreamWriter(String.Format(@"{0}\Log_{1}.txt", error_folder, timestamp));
        }
        else
        {
            log = File.AppendText(String.Format(@"{0}\Log_{1}.txt", error_folder, timestamp));
        }

        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];

        // Write to the file:
        log.WriteLine(Environment.NewLine + DateTime.Now);
        log.WriteLine("------------------------------------------------------------------------------------------------");
        log.WriteLine("Controller Name :- " + controllerName);
        log.WriteLine("Action Method Name :- " + actionName);
        log.WriteLine("------------------------------------------------------------------------------------------------");
        log.WriteLine(objClass);
        log.WriteLine(strLogText);
        log.WriteLine();

        // Close the stream:
        log.Close();
        filterContext.HttpContext.Session.Abandon();
        filterContext.Result = new RedirectToRouteResult
         (new RouteValueDictionary 
         {
                 {"controller", "Errorview"}, {"action", "Error"}
         });

    }

}

2 단계 : 텍스트 파일이 저장 될 서버 또는 로컬 드라이브에 물리적 경로 추가

<add key="ErrorLogPath" value="C:\ErrorLog\DemoMVC\" />

3 단계 : 오류 ActionMethod가있는 Errorview 컨트롤러 추가

4 단계 : Error.cshtml 추가 보기에서 사용자 정의 오류 메시지보기 및 표시

5 단계 : FilterConfig 클래스에 ErrorLogger 필터 등록

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ErrorLogger());
    }
}

6 단계 : Global.asax에 FilterConfig 등록

여기에 이미지 설명을 입력하십시오.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow