Exemple #1
0
        private static async Task WriteExceptionAsync(HttpContext context, Exception exception)
        {
            //记录日志
            Log4NetUtil.LogError(exception.GetBaseException().ToString(), exception);

            //返回友好的提示
            var response = context.Response;

            //状态码
            if (exception is Exception)
            {
                response.StatusCode = (int)HttpStatusCode.BadRequest;
            }

            response.ContentType = "application/json";
            await response.WriteAsync(JsonConvert.SerializeObject(new CustomExceptionResultModel(response.StatusCode, exception.GetBaseException()))).ConfigureAwait(false);
        }
Exemple #2
0
 public void OnException(ExceptionContext context)
 {
     try
     {
         Log4NetUtil.LogError("全局异常", context.Exception);
         if (context.HttpContext.Request.IsHttps)
         {
             context.Result = new JsonResult(context.Exception.Message);
         }
         else
         {
             context.Result = new RedirectToActionResult("Error", "Home", new { });
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
     context.ExceptionHandled = true; // 注意:如果不添加这句代码,程序不会自动断路,会继续向下进行。
 }
Exemple #3
0
        public IActionResult Login([FromBody] UserInfoModels user)
        {
            var json = new JsonResultModels();

            try
            {
                if (string.IsNullOrWhiteSpace(user.UserName) || string.IsNullOrWhiteSpace(user.Password))
                {
                    json.Code = 201;
                    json.Msg  = "用户名密码不能为空";
                    return(Ok(json));
                }
                else
                {
                    var UserDate = _userBLL.CheckUser(user.UserName, user.Password);
                    if (UserDate == null)
                    {
                        json.Code = 400;
                        json.Msg  = "登录失败:用户不存在!";
                    }
                    else
                    {
                        Dictionary <string, string> keyValues = new Dictionary <string, string> {
                            { "UserName", UserDate.UserName }
                        };
                        json.Code    = 200;
                        json.Msg     = "登录成功";
                        json.TnToken = _tokenHelper.CreateToken(keyValues);
                    }
                }
            }
            catch (Exception ex)
            {
                json.Code = 400;
                json.Msg  = "登录失败:" + ex.Message;
                Log4NetUtil.LogError(json.Msg, ex);
            }
            Log4NetUtil.LogInfo(json.Msg);
            return(Ok(json));
        }
Exemple #4
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await Next(context);
            }
            catch (Exception e)
            {
                context.Response.Clear();
                context.Response.StatusCode = StatusCodes.Status200OK;

                Log4NetUtil.LogError("全局异常", e);

                if (context.Request.IsHttps)
                {
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(new { Code = 500, Message = e.Message }));
                }
                else
                {
                    context.Response.Redirect("/Home/Error");
                }
            }
        }
        /// <summary>
        /// 执行响应流指向新对象
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            context.Request.EnableBuffering();
            var api = new HttpContextMessage
            {
                RequestMethod      = context.Request.Method,
                ResponseStatusCode = context.Response.StatusCode,
                RequestQurey       = context.Request.QueryString.ToString(),
                RequestContextType = context.Request.ContentType,
                RequestHost        = context.Request.Host.ToString(),
                RequestPath        = context.Request.Path,
                RequestScheme      = context.Request.Scheme,
                RequestLocalIp     = (context.Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + context.Request.HttpContext.Connection.LocalPort),
                RequestRemoteIp    = (context.Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() + ":" + context.Request.HttpContext.Connection.RemotePort)
            };

            var request  = context.Request.Body;
            var response = context.Response.Body;
            //请求序列号
            string serialNumber = "";

            try
            {
                using (var newRequest = new MemoryStream())
                {
                    //替换request流
                    context.Request.Body = newRequest;

                    using (var newResponse = new MemoryStream())
                    {
                        //替换response流
                        context.Response.Body = newResponse;

                        using (var reader = new StreamReader(request))
                        {
                            //读取原始请求流的内容
                            api.RequestBody = await reader.ReadToEndAsync();

                            if (string.IsNullOrEmpty(api.RequestBody))
                            {
                                //await _next.Invoke(context);
                            }
                            else
                            {
                                JObject jObject = JObject.Parse(api.RequestBody);
                                if (jObject["SerialNumber"] != null)
                                {
                                    if (!string.IsNullOrEmpty(jObject["SerialNumber"].ToString()))
                                    {
                                        serialNumber = jObject["SerialNumber"].ToString();
                                    }
                                }
                            }
                        }

                        using (var writer = new StreamWriter(newRequest))
                        {
                            await writer.WriteAsync(api.RequestBody);

                            await writer.FlushAsync();

                            newRequest.Position  = 0;
                            context.Request.Body = newRequest;
                            await _next(context);
                        }

                        using (var reader = new StreamReader(newResponse))
                        {
                            newResponse.Position = 0;
                            api.ResponseBody     = await reader.ReadToEndAsync();

                            try
                            {
                                JObject resJObect = JObject.Parse(api.ResponseBody);
                                resJObect["SerialNumber"] = serialNumber;
                                api.ResponseBody          = resJObect.ToJson();
                            }
                            catch
                            {
                            }
                        }

                        context.Response.Clear();

                        using (var writer = new StreamWriter(response, System.Text.Encoding.UTF8))
                        {
                            await writer.WriteAsync(api.ResponseBody);

                            await writer.FlushAsync();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ResponseResult responseResult = new ResponseResult();
                responseResult.SerialNumber = serialNumber;
                context.Response.Clear();
                context.Response.StatusCode = StatusCodes.Status200OK;
                responseResult.Code         = ResponseResultType.Error;
                responseResult.Message      = "对不起,系统开小差了!!!";
                //记录异常
                Log4NetUtil.LogError("全局捕获异常SerialNumber:" + responseResult.SerialNumber, ex);
                using (var writer = new StreamWriter(response))
                {
                    await writer.WriteAsync(responseResult.ToJson());

                    await writer.FlushAsync();
                }
            }
            finally
            {
                context.Request.Body  = request;
                context.Response.Body = response;
            }

            // 响应完成时存入缓存
            context.Response.OnCompleted(() =>
            {
                //记录响应报文
                Log4NetUtil.LogDebug(api.ToString());
                return(Task.CompletedTask);
            });
        }