英文:
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() => _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<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();
答案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<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectioin")));
//DI for IHttpContextAccessor
builder.Services.AddHttpContextAccessor();
//Or builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Here is the reference.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论