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

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

save messages in the console log to a class

问题

我有两个名为Issues和Requestmessages的类。我使用Visual Studio和.NET Core以及Swagger构建了一个简单的API。我包括了获取、添加和推送方法。我想要能够在每次使用获取、添加和推送方法时向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);

// 将服务添加到容器中。

builder.Services.AddControllers();
// 了解有关配置Swagger/OpenAPI的更多信息: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();

// 配置HTTP请求管道。
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();

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

英文:

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.

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() =&gt; _httpContextAccessor.HttpContext.Request.Body.Position = 0;
    }
}

Here is the program class that I used.

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&lt;AppDbContext&gt;(o =&gt; o.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnectioin&quot;)));


builder.Services.AddHttpLogging(logging =&gt;
{
    logging.LoggingFields = HttpLoggingFields.All;
    logging.RequestHeaders.Add(&quot;sec-ch-ua&quot;);
    logging.ResponseHeaders.Add(&quot;MyResponseHeader&quot;);
    logging.MediaTypeOptions.AddText(&quot;application/javascript&quot;);
    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&lt;RequestMessageLogger&gt;();
app.UseHttpLogging();
app.Use(async (context, next) =&gt;
{
    context.Response.Headers[&quot;MyResponseHeader&quot;] =
        new string[] { &quot;My Response Header Value&quot; };

    await next();
});

app.UseHttpsRedirection();


app.UseAuthorization();

app.MapControllers();

app.Run();

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

答案1

得分: 1

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

尝试添加以下代码:

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

这里 是参考链接。

英文:

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

Try adding the below code:

builder.Services.AddDbContext&lt;AppDbContext&gt;(o =&gt; o.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnectioin&quot;)));
//DI for IHttpContextAccessor
builder.Services.AddHttpContextAccessor();
//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:

确定