private RequestLogEntity MapToRequestLogEntity(HttpRequest httpRequest) { var res = new RequestLogEntity() { CreatedBy = Guid.Empty, DateCreated = DateTime.UtcNow, Headers = JsonConvert.SerializeObject(httpRequest.Headers), Cookies = JsonConvert.SerializeObject(httpRequest.Cookies), Path = httpRequest.Path.ToString(), PathBase = httpRequest.PathBase.ToString(), Method = httpRequest.Method, Protocol = httpRequest.Protocol, QueryString = httpRequest.QueryString.ToString(), Query = JsonConvert.SerializeObject(httpRequest.Query) }; if (httpRequest.Body.CanSeek) { httpRequest.Body.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(httpRequest.Body)) { res.Body = reader.ReadToEnd(); }; } return(res); }
/// <summary> /// 创建前台页面访问日志 /// </summary> /// <param name="accessLogEntity"></param> private void InsertRequestLog(RequestLogEntity entity) { entity = InitRequestLog(entity, true); RequestLogApp requestLogApp = new RequestLogApp(); requestLogApp.Createlog(entity); }
private async Task FormatRequest(HttpRequest context, RequestLogEntity requestLog) { string bodyAsText = string.Empty; try { var body = context.Body; //This line allows us to set the reader for the request back at the beginning of its stream. context.EnableRewind(); //We now need to read the request stream. First, we create a new byte[] with the same length as the request stream... var buffer = new byte[Convert.ToInt32(context.ContentLength)]; //...Then we copy the entire request stream into the new buffer. await context.Body.ReadAsync(buffer, 0, buffer.Length); //We convert the byte[] into a string using UTF8 encoding... bodyAsText = Encoding.UTF8.GetString(buffer); //..and finally, assign the read body back to the request body, which is allowed because of EnableRewind() context.Body = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsText)); BaseRequest request = JsonConvert.DeserializeObject <BaseRequest>(bodyAsText); requestLog.RequestId = request.requestId; } catch { } requestLog.Request = bodyAsText; }
private async Task LogRequest(HttpContext context) { Stopwatch sw = new Stopwatch(); sw.Start(); RequestLogEntity requestLog = new RequestLogEntity(); context.Items["RequestLogEntity"] = requestLog; await FormatRequest(context.Request, requestLog); var originalBodyStream = context.Response.Body; //Create a new memory stream... using (var responseBody = new MemoryStream()) { //...and use that for the temporary response body context.Response.Body = responseBody; //Continue down the Middleware pipeline, eventually returning to this class await _next(context); //Format the response from the server await FormatResponse(context.Response, requestLog, sw); await responseBody.CopyToAsync(originalBodyStream); } }
private async Task FormatResponse(HttpResponse response, RequestLogEntity requestLog, Stopwatch sw) { try { string text = string.Empty; //We need to read the response stream from the beginning... response.Body.Seek(0, SeekOrigin.Begin); //...and copy it into a string text = await new StreamReader(response.Body).ReadToEndAsync(); //We need to reset the reader for the response so that the client can read it. response.Body.Seek(0, SeekOrigin.Begin); requestLog.Response = text; //BaseResponse<string> res = JsonConvert.DeserializeObject<BaseResponse<string>>(text); JObject obj = JObject.Parse(text); Object objResult = obj["result"]; requestLog.ResponseCode = null == objResult ? string.Empty : objResult.ToString(); sw.Stop(); requestLog.ResponseTime = sw.ElapsedMilliseconds; _logger.LogInformation(JsonConvert.SerializeObject(requestLog)); } catch { } }
/// <summary> /// 创建请求结束日志 /// </summary> /// <param name="context"></param> public void AddEndRequestLog(System.Web.HttpContext context) { if (Code.ConfigHelp.configHelp.ISPROREQUESTLOG) { RequestLogEntity entity = InitEndRequestLog(context); CreateRequestLog(entity, true); } }
/// <summary> /// 处理访问参数 /// </summary> /// <param name="context"></param> /// <returns></returns> private RequestLogEntity InitRequestLog(RequestLogEntity entity, bool IsProcessWebSite) { WebSiteApp app = new WebSiteApp(); WebSiteEntity webSiteEntity = app.GetModelByUrlHost(entity.WebSiteName); if (webSiteEntity != null) { entity.WebSiteId = webSiteEntity.Id; } return(entity); }
public bool LogRequest(string actionMethod, string controller, int userId) { RequestLogEntity log = new RequestLogEntity() { ActionMethodName = actionMethod, ControllerName = controller, UserId = userId, DateTime = DateTime.Now }; return(_employeeBL.LogRequest(log)); }
public void SubmitForm(RequestLogEntity accessLogEntity, string keyValue) { if (!string.IsNullOrEmpty(keyValue)) { accessLogEntity.Modify(keyValue); service.Update(accessLogEntity); } else { accessLogEntity.Create(); service.Insert(accessLogEntity); } }
/// <summary> /// 处理访问参数 /// </summary> /// <param name="context"></param> /// <returns></returns> private RequestLogEntity InitEndRequestLog(System.Web.HttpContext context) { string realIp = GetRealClientIp(context); string urlHost = new RequestHelp().GetHost(context); string urlRaw = context.Request.RawUrl.ToString(); RequestLogEntity entity = new RequestLogEntity(); entity.UrlAddress = context.Request.Url.ToString(); entity.UrlHost = urlHost; entity.UrlRaw = urlRaw; entity.WebSiteName = urlHost; if (context.Session != null) { entity.SessionID = context.Session.SessionID; } if (context.Request != null) { entity.IPAddress = realIp; entity.Browser = context.Request.Browser.Browser; entity.BrowserID = context.Request.Browser.Id; entity.BrowserVersion = context.Request.Browser.Version; entity.BrowserType = context.Request.Browser.Type; entity.BrowserPlatform = context.Request.Browser.Platform; if (context.Request.UrlReferrer != null) { entity.PUrlAddress = context.Request.UrlReferrer.ToString(); } } entity.EnabledMark = true; HttpCookie cookie = context.Request.Cookies.Get(CLINETID); if (cookie != null && !string.IsNullOrEmpty(cookie.Value)) { entity.ClientID = cookie.Value; } else { string clientIds = Guid.NewGuid().ToString(); entity.ClientID = clientIds; cookie = new HttpCookie(CLINETID); cookie.Name = CLINETID; cookie.Value = clientIds; cookie.Expires = DateTime.Now.AddYears(1); entity.ClientID = clientIds; context.Response.Cookies.Set(cookie); } entity.StartDateTime = context.Timestamp; return(entity); }
public bool LogRequest(RequestLogEntity logData) { RequestCallLog requestLog = new RequestCallLog() { ActionMethodName = logData.ActionMethodName, ControllerName = logData.ControllerName, DateTime = logData.DateTime, UserId = logData.UserId }; _database.RequestCallLogs.Add(requestLog); int result = _database.SaveChanges(); return(result > 0 ? true : false); }
/// <summary> /// 创建前台页面访问日志 /// </summary> /// <param name="accessLogEntity"></param> public void CreateRequestLog(RequestLogEntity entity, bool IsAsync) { if (IsAsync) { Thread thread = new Thread(new ThreadStart(() => { InsertRequestLog(entity); })); thread.Start(); } else { InsertRequestLog(entity); } }
/// <summary> /// 创建系统请求访问日志 /// </summary> /// <param name="accessLogEntity"></param> public void CreateRequestLog(RequestLogEntity entity) { InsertRequestLog(entity); }
/// <summary> /// 创建访问日志 /// </summary> /// <param name="accessLogEntity"></param> public void Createlog(RequestLogEntity accessLogEntity) { accessLogEntity.Id = Common.GuId(); accessLogEntity.EndDateTime = DateTime.Now; service.Insert(accessLogEntity); }
public async Task InvokeAsync(HttpContext context) { _stopwatch.Restart(); var request = context.Request; var entity = new RequestLogEntity() { TranceId = Guid.NewGuid().ToString(), ClientIp = GetClientIP(context), RequestMethod = request.Method, RequestHeaders = JsonSerializer.Serialize(request.Headers.ToDictionary(x => x.Key, v => string.Join(";", v.Value.ToList()))), Url = request.Path, ExecutedTime = DateTime.Now, }; //注意:文件上传接口可能需要单独处理 //miniprofiler一直请求接口结果,所以此处过滤该请求信息(只保留正常的接口请求信息) if (entity.Url.Contains("api")) { switch (request.Method.ToLower()) { case "get": entity.RequestParamters = request.QueryString.Value; break; case "post": //确保请求体信息可被多次读取 request.EnableBuffering(); var reader = new StreamReader(request.Body, Encoding.UTF8); entity.RequestParamters = await reader.ReadToEndAsync(); //流位置重置为0 request.Body.Position = 0; break; case "put": //确保请求体信息可被多次读取 request.EnableBuffering(); var readers = new StreamReader(request.Body, Encoding.UTF8); entity.RequestParamters = await readers.ReadToEndAsync(); //流位置重置为0 request.Body.Position = 0; break; case "delete": entity.RequestParamters = request.QueryString.Value; break; case "options": entity.RequestParamters = string.Empty; break; } // 获取Response.Body内容 var originalBodyStream = context.Response.Body; //引用类型,共享内存地址,所以memory也会被赋值 using (var memory = new MemoryStream()) { context.Response.Body = memory; await _next(context); GetCustomAttribute(context); _logger.LogInformation("开始处理请求结果。。。。。。。。。"); ResponseDataLog(memory); memory.Position = 0; await memory.CopyToAsync(originalBodyStream); } context.Response.OnCompleted(() => { _stopwatch.Stop(); entity.ElaspedTime = $"{_stopwatch.ElapsedMilliseconds}ms"; using (var scope = _serviceProvider.CreateScope()) { var _services = _serviceProvider.GetRequiredService <IRequestLogServices>(); _services.Insert(entity, true); } _logger.LogInformation("请求结果处理结束。。。。。。。。。"); return(Task.CompletedTask); }); } else { await _next(context); } }
public bool LogRequest(RequestLogEntity logEntity) { return(_employeeDAL.LogRequest(logEntity)); }