ASP.NET는 차단기를 통해 오류 로그의 예제 코드를 기록합니다.

3933 단어 ASP.NET차단기

앞말


주로 실현된 오류 로그 차단을 기록합니다. 차단기에서 되돌아오는 정보를 제어하고 오류 정보를 처리한 후에 요청자에게 되돌려줍니다.

차단기


차단기는 필터라고도 부른다.
asp.net mvc 자체는 세 가지 차단기를 가지고 있습니다. 액션 차단기, Result 차단기, Exception 차단기입니다.응용 프로그램에서 흔히 볼 수 있는 차단기는 로그 차단기(Action 차단기)와 비정상 처리 차단기(Exception 차단기)가 있습니다.
자바리spring mvc도 차단기를 사용하여 업무 논리에 관여하지 않는 일을 한다. 예를 들어 Handler Interceptor 인터페이스를 실현하는 것이다.
차단기는 AOP의 응용 프로그램입니다.
차단기가 해결해야 할 문제:
1. 코드 재사용.차단기는 다시 사용할 수 있다
2. 직책이 단일하다.예를 들어 요리사는 요리만 책임지고 전기의 채소 씻기, 후속적인 배달 업무를 상관하지 않는다.음식이 변질돼도 그냥 소리 지르면 사람이 처리한다.
이번에는 저희가 오류 로그를 기록하는 데 쓰겠습니다.

코드 실전


차단기

    /// <summary>
    ///  
    /// </summary>
    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
    public class ApiErrorHandleAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnException(actionExecutedContext);
            actionExecutedContext.Response = GetResponse(actionExecutedContext);
        }

        /// <summary>
        ///  
        /// </summary>
        private HttpResponseMessage GetResponse(HttpActionExecutedContext actionExecutedContext)
        {
            var requesthost = actionExecutedContext.ActionContext.Request.RequestUri.ToString();// , ip 
            var method = actionExecutedContext.ActionContext.Request.Method.ToString();// POST/GET/PUT/DELETE ……
            var controller = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;// :xxx.WebAPI.Controllers.xxxController
            var action = actionExecutedContext.ActionContext.ActionDescriptor.ActionName; // 
            var paramters = actionExecutedContext.ActionContext.ActionArguments; // 
            var ip = HttpContext.Current.Request.UserHostAddress;
           
            LogHelper.Error($" :URL:{actionExecutedContext.Request.RequestUri},-- :{paramters.ToJson()},--actionExecutedContext.Exception:{actionExecutedContext.Exception.ToJson()}");
            var response = new { code = 506, message = $"{actionExecutedContext.Exception.Message},URL:{actionExecutedContext.Request.RequestUri}", ex = actionExecutedContext.Exception };
           
            return JsonHelper.ToHttpResponseMessage(response);
        }

    }
도구류 방법

    public static class JsonHelper
    {
        /// <summary>
        ///  json HttpResponseMessage
        /// </summary>
        public static HttpResponseMessage ToHttpResponseMessage(object obj)
        {
            string str;
            if (obj is string || obj is char)
            {
                str = obj.ToString();
            }
            else
            {
                str = obj.ToJson();
            }
            var result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

        /// <summary>
        ///  json , 
        /// </summary>
        /// <param name="obj"> </param>
        /// <returns>json </returns>
        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, DateFormatString = "yyyy-MM-dd HH:mm:ss" });
        }
    }
지금까지 ASP였습니다.NET는 차단기를 통해 오류 로그의 예제 코드에 대한 자세한 내용을 기록하고 ASP에 대한 자세한 내용을 제공합니다.NET가 잘못된 로그를 기록한 자료는 다른 관련 글을 참고하세요!

좋은 웹페이지 즐겨찾기