将消息保存到控制台日志中的一个类中

huangapple go评论135阅读模式
英文:

save messages in the console log to a class

问题

我有两个名为Issues和Requestmessages的类。我使用Visual Studio和.NET Core以及Swagger构建了一个简单的API。我包括了获取、添加和推送方法。我想要能够在每次使用获取、添加和推送方法时向RequestMessage类添加信息。

  1. using System.ComponentModel.DataAnnotations;
  2. namespace APIExample.Models
  3. {
  4. public class Issues
  5. {
  6. public int Id { get; set; }
  7. [Required]
  8. public string Title { get; set; }
  9. [Required]
  10. public string Description { get; set; }
  11. public Priority Priority { get; set; }
  12. public IssueType IssueType { get; set; }
  13. public DateTime Created { get; set; }
  14. public DateTime? Completed { get; set; }
  15. }
  16. public enum Priority
  17. {
  18. Low, Medium, High
  19. }
  20. public enum IssueType
  21. {
  22. Feature, Bug, Documentation
  23. }
  24. }
  1. using Microsoft.EntityFrameworkCore;
  2. using System.ComponentModel.DataAnnotations;
  3. namespace APIExample
  4. {
  5. [Keyless]
  6. public class RequestMessage
  7. {
  8. [Required]
  9. public string Message { get; set; }
  10. public DateTime Received { get; set; }
  11. [Required]
  12. public string Uri { get; set; }
  13. }
  14. }
  1. namespace APIExample
  2. {
  3. public class RequestMessageLogger: IRequestMessageLogger
  4. {
  5. private readonly AppDbContext _dbContext;
  6. private readonly IHttpContextAccessor _httpContextAccessor;
  7. public RequestMessageLogger(AppDbContext dbContext, IHttpContextAccessor httpContextAccessor)
  8. {
  9. _dbContext = dbContext;
  10. _httpContextAccessor = httpContextAccessor;
  11. }
  12. public string bodyAsString;
  13. public void LogRequest()
  14. {
  15. if (_httpContextAccessor.HttpContext.Request.Body.CanSeek)
  16. {
  17. string bodyAsString;
  18. RewindStream();
  19. using StreamReader reader = new StreamReader(_httpContextAccessor.HttpContext.Request.Body, Encoding.UTF8, true, 1024, true);
  20. bodyAsString = reader.ReadToEnd();
  21. RewindStream();
  22. }
  23. var uri = _httpContextAccessor.HttpContext.Request.GetDisplayUrl();
  24. _dbContext.requestMessages.Add(new RequestMessage { Message = bodyAsString, Received = DateTime.Now, Uri = uri });
  25. _dbContext.SaveChanges();
  26. }
  27. private void RewindStream() => _httpContextAccessor.HttpContext.Request.Body.Position = 0;
  28. }
  29. }

这是我使用的程序类。

  1. using APIExample;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.HttpLogging;
  5. using Microsoft.EntityFrameworkCore;
  6. var builder = WebApplication.CreateBuilder(args);
  7. // 将服务添加到容器中。
  8. builder.Services.AddControllers();
  9. // 了解有关配置Swagger/OpenAPI的更多信息:https://aka.ms/aspnetcore/swashbuckle
  10. builder.Services.AddEndpointsApiExplorer();
  11. builder.Services.AddSwaggerGen();
  12. builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectioin")));
  13. builder.Services.AddHttpLogging(logging =>
  14. {
  15. logging.LoggingFields = HttpLoggingFields.All;
  16. logging.RequestHeaders.Add("sec-ch-ua");
  17. logging.ResponseHeaders.Add("MyResponseHeader");
  18. logging.MediaTypeOptions.AddText("application/javascript");
  19. logging.RequestBodyLogLimit = 4096;
  20. logging.ResponseBodyLogLimit = 4096;
  21. });
  22. var app = builder.Build();
  23. // 配置HTTP请求管道。
  24. if (app.Environment.IsDevelopment())
  25. {
  26. app.UseSwagger();
  27. app.UseSwaggerUI();
  28. }
  29. app.UseStaticFiles();
  30. //app.UseMiddleware<RequestMessageLogger>();
  31. app.UseHttpLogging();
  32. app.Use(async (context, next) =>
  33. {
  34. context.Response.Headers["MyResponseHeader"] =
  35. new string[] { "My Response Header Value" };
  36. await next();
  37. });
  38. app.UseHttpsRedirection();
  39. app.UseAuthorization();
  40. app.MapControllers();
  41. app.Run();

将消息保存到控制台日志中的一个类中

英文:

I have a two classes called Issues and Requestmessages. I build simple api using Visual studio and .NET Core and swagger. I included get put and push method. I want to be able to add information to the RequestMessage class everytime the get, put and push methods are used.

  1. using System.ComponentModel.DataAnnotations;
  2. namespace APIExample.Models
  3. {
  4. public class Issues
  5. {
  6. public int Id { get; set; }
  7. [Required]
  8. public string Title { get; set; }
  9. [Required]
  10. public string Description { get; set; }
  11. public Priority Priority { get; set; }
  12. public IssueType IssueType { get; set; }
  13. public DateTime Created { get; set; }
  14. public DateTime? Completed { get; set; }
  15. }
  16. public enum Priority
  17. {
  18. Low, Medium, High
  19. }
  20. public enum IssueType
  21. {
  22. Feature, Bug, Documentation
  23. }
  24. }
  1. using Microsoft.EntityFrameworkCore;
  2. using System.ComponentModel.DataAnnotations;
  3. namespace APIExample
  4. {
  5. [Keyless]
  6. public class RequestMessage
  7. {
  8. [Required]
  9. public string Message { get; set; }
  10. public DateTime Received { get; set; }
  11. [Required]
  12. public string Uri { get; set; }
  13. }
  14. }
  1. namespace APIExample
  2. {
  3. public class RequestMessageLogger: IRequestMessageLogger
  4. {
  5. private readonly AppDbContext _dbContext;
  6. private readonly IHttpContextAccessor _httpContextAccessor;
  7. public RequestMessageLogger(AppDbContext dbContext, IHttpContextAccessor httpContextAccessor)
  8. {
  9. _dbContext = dbContext;
  10. _httpContextAccessor = httpContextAccessor;
  11. }
  12. public string bodyAsString;
  13. public void LogRequest()
  14. {
  15. if (_httpContextAccessor.HttpContext.Request.Body.CanSeek)
  16. {
  17. string bodyAsString;
  18. RewindStream();
  19. using StreamReader reader = new StreamReader(_httpContextAccessor.HttpContext.Request.Body, Encoding.UTF8, true, 1024, true);
  20. bodyAsString = reader.ReadToEnd();
  21. RewindStream();
  22. }
  23. var uri = _httpContextAccessor.HttpContext.Request.GetDisplayUrl();
  24. _dbContext.requestMessages.Add(new RequestMessage { Message = bodyAsString, Received = DateTime.Now, Uri = uri });
  25. _dbContext.SaveChanges();
  26. }
  27. private void RewindStream() =&gt; _httpContextAccessor.HttpContext.Request.Body.Position = 0;
  28. }
  29. }

Here is the program class that I used.

  1. using APIExample;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.HttpLogging;
  5. using Microsoft.EntityFrameworkCore;
  6. var builder = WebApplication.CreateBuilder(args);
  7. // Add services to the container.
  8. builder.Services.AddControllers();
  9. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  10. builder.Services.AddEndpointsApiExplorer();
  11. builder.Services.AddSwaggerGen();
  12. builder.Services.AddDbContext&lt;AppDbContext&gt;(o =&gt; o.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnectioin&quot;)));
  13. builder.Services.AddHttpLogging(logging =&gt;
  14. {
  15. logging.LoggingFields = HttpLoggingFields.All;
  16. logging.RequestHeaders.Add(&quot;sec-ch-ua&quot;);
  17. logging.ResponseHeaders.Add(&quot;MyResponseHeader&quot;);
  18. logging.MediaTypeOptions.AddText(&quot;application/javascript&quot;);
  19. logging.RequestBodyLogLimit = 4096;
  20. logging.ResponseBodyLogLimit = 4096;
  21. });
  22. var app = builder.Build();
  23. // Configure the HTTP request pipeline.
  24. if (app.Environment.IsDevelopment())
  25. {
  26. app.UseSwagger();
  27. app.UseSwaggerUI();
  28. }
  29. app.UseStaticFiles();
  30. //app.UseMiddleware&lt;RequestMessageLogger&gt;();
  31. app.UseHttpLogging();
  32. app.Use(async (context, next) =&gt;
  33. {
  34. context.Response.Headers[&quot;MyResponseHeader&quot;] =
  35. new string[] { &quot;My Response Header Value&quot; };
  36. await next();
  37. });
  38. app.UseHttpsRedirection();
  39. app.UseAuthorization();
  40. app.MapControllers();
  41. app.Run();

将消息保存到控制台日志中的一个类中

答案1

得分: 1

我无法在 program.cs 文件中找到对 IHttpContextAccessor 的依赖注入。

尝试添加以下代码:

  1. builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
  2. // 为 IHttpContextAccessor 添加依赖注入
  3. builder.Services.AddHttpContextAccessor();
  4. // 或者使用 builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

这里 是参考链接。

英文:

I cannot see dependency injection for IHttpContextAccessor in the program.cs file.

Try adding the below code:

  1. builder.Services.AddDbContext&lt;AppDbContext&gt;(o =&gt; o.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnectioin&quot;)));
  2. //DI for IHttpContextAccessor
  3. builder.Services.AddHttpContextAccessor();
  4. //Or builder.Services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();

Here is the reference.

huangapple
  • 本文由 发表于 2023年1月9日 15:57:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定