.net 将控制台日志中的消息保存到类

x6yk4ghg  于 2023-01-10  发布在  .NET
关注(0)|答案(1)|浏览(268)

我有两个类叫问题和Requestmessages。我用Visual Studio和. NET核心和swagger构建简单的api。我包括get put和push方法。我希望每次使用get,put和push方法时都能向RequestMessage类添加信息。

using System.ComponentModel.DataAnnotations;

namespace APIExample.Models
{
    public class Issues
    {
        public int Id { get; set; }
        [Required]
        public string Title { get; set; }
        [Required]
        public string Description { get; set; }
        public Priority Priority { get; set; }
        public IssueType IssueType { get; set; }
        public DateTime Created { get; set; }
        public DateTime? Completed { get; set; }
    }

    public enum Priority
    {
        Low, Medium, High
    }
    public enum IssueType
    {
        Feature, Bug, Documentation
    }
}
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace APIExample
{
    [Keyless]
    public class RequestMessage
    {
        [Required]
        public string Message { get; set; }
        public DateTime Received { get; set; }
        [Required]
        public string Uri { get; set; }
    }
}
namespace APIExample
{
    public class RequestMessageLogger: IRequestMessageLogger
    {
        private readonly AppDbContext _dbContext;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public RequestMessageLogger(AppDbContext dbContext, IHttpContextAccessor httpContextAccessor)
        {
            _dbContext = dbContext;
            _httpContextAccessor = httpContextAccessor;
        }
        public string bodyAsString;
        public void LogRequest()
        {
            
            if (_httpContextAccessor.HttpContext.Request.Body.CanSeek)
           {
                string bodyAsString;
                 RewindStream();
                
                using StreamReader reader = new StreamReader(_httpContextAccessor.HttpContext.Request.Body, Encoding.UTF8, true, 1024, true);
                bodyAsString = reader.ReadToEnd();

                RewindStream();
           }

            var uri = _httpContextAccessor.HttpContext.Request.GetDisplayUrl();

            _dbContext.requestMessages.Add(new RequestMessage { Message = bodyAsString, Received = DateTime.Now, Uri = uri });
            
            _dbContext.SaveChanges();
        }

        private void RewindStream() => _httpContextAccessor.HttpContext.Request.Body.Position = 0;
    }
}

这是我使用的程序类。

using APIExample;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectioin")));

builder.Services.AddHttpLogging(logging =>
{
    logging.LoggingFields = HttpLoggingFields.All;
    logging.RequestHeaders.Add("sec-ch-ua");
    logging.ResponseHeaders.Add("MyResponseHeader");
    logging.MediaTypeOptions.AddText("application/javascript");
    logging.RequestBodyLogLimit = 4096;
    logging.ResponseBodyLogLimit = 4096;
    
});


var app = builder.Build();



// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseStaticFiles();
//app.UseMiddleware<RequestMessageLogger>();
app.UseHttpLogging();
app.Use(async (context, next) =>
{
    context.Response.Headers["MyResponseHeader"] =
        new string[] { "My Response Header Value" };

    await next();
});

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

bvjveswy

bvjveswy1#

我在program.cs文件中看不到IHttpContextAccessor的依赖注入。
尝试添加以下代码:

builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectioin")));
//DI for IHttpContextAccessor
builder.Services.AddHttpContextAccessor();
//Or builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

这里是参考。

相关问题