ApiLogService.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using Datory;
  5. using GxPress.Common.AppOptions;
  6. using GxPress.Common.Tools;
  7. using GxPress.Entity;
  8. using GxPress.Service.Interface;
  9. using Microsoft.AspNetCore.Http;
  10. using Microsoft.Extensions.Configuration;
  11. using Microsoft.Extensions.Options;
  12. namespace GxPress.Service.Implement
  13. {
  14. public class ApiLogService : IApiLogService
  15. {
  16. private readonly IConfiguration _configuration;
  17. private readonly Repository<UserLogin> _repository;
  18. private readonly Repository<User> _userRepository;
  19. public ApiLogService(IConfiguration configuration, IOptionsMonitor<DatabaseOptions> dbOptionsAccessor)
  20. {
  21. _configuration = configuration;
  22. var databaseType =
  23. StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
  24. //_connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
  25. var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
  26. _repository = new Repository<UserLogin>(database);
  27. _userRepository = new Repository<User>(database);
  28. }
  29. public async Task DataSave(HttpContext context, long responseTime, int userId)
  30. {
  31. var isLog = _configuration.GetValue<bool>("ApiLog:IsEnable");
  32. // if (isLog)
  33. // {
  34. var requestMethod = context.Request.Method;
  35. var requestURL = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}";
  36. //var accessToken = context.GetTokenAsync("access_token").Result;//添加身份验证的项目可以使用此方法获取到access_toekn
  37. var accessToken = string.Empty;
  38. var requestBody = string.Empty;
  39. if (requestMethod == "POST")
  40. {
  41. context.Request.Body.Seek(0, SeekOrigin.Begin);
  42. var _reader = new StreamReader(context.Request.Body);
  43. requestBody = _reader.ReadToEnd();
  44. }
  45. var model = new UserLogin
  46. {
  47. AccessToken = accessToken,
  48. AccessTime = DateTime.Now,
  49. AccessAction = requestMethod,
  50. AccessApiUrl = requestURL,
  51. QueryString = context.Request.QueryString.ToString(),
  52. Body = requestBody,
  53. HttpStatus = context.Response.StatusCode,
  54. ClientIP = context.Connection.RemoteIpAddress.ToString(),
  55. ResponseTime = responseTime,
  56. UserId = userId
  57. };
  58. await _repository.InsertAsync(model);
  59. //
  60. await _userRepository.UpdateAsync(Q.Where(nameof(User.Id), userId).Set(nameof(User.LoginTime), DateTime.Now));
  61. //}
  62. }
  63. }
  64. }