C# dotnetcore 异常过滤器

    /// 
    /// 异常过滤器
    /// 
    public class ExceptionFilter : Attribute, IExceptionFilter
    {

        /// 
        /// logService
        /// 
        public readonly ILogService logService;

        /// 
        /// 
        /// 
        /// 
        public ExceptionFilter(ILogService logService) {

            this.logService = logService;
        }


        /// 
        /// 
        /// 
        /// 
        public void OnException(ExceptionContext context)
        {

            string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();  //得到请求方的ip地址
            var reuslt = context.Exception.ToString();                              //异常结果
            string url = context.HttpContext.Request.Path.Value;                    //url


            IQueryCollection queryParameters = context.HttpContext.Request.Query;
            string token = queryParameters["token"].ToString();
            UserRedisModel userModel = RedisHelper.Get(token);


            var isok = logService.WriteLog(ip, context.Exception.ToString(), userModel == null ? 0 : userModel.UserId, url);


            context.Result = new ContentResult
            {
                Content = new { code = 5, data = "", msg = "404" }.ObjectToJson(),
                StatusCode = StatusCodes.Status200OK,
                ContentType = "text/html;charset=utf-8"

            };

            context.ExceptionHandled = false;
        }


    }

 

你可能感兴趣的:(C#,.net)