You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET Core API的GET/PUT/POST请求时写入日志到RequestMessage类

.NET Core API 请求日志记录实现

我定义了Issues和RequestMessage两个类,基于Visual Studio与.NET Core构建了集成Swagger的简易API,包含GET、PUT和POST方法。希望每次调用这些方法时,都能将请求信息写入RequestMessage类中。

以下是我的代码实现:

Issues 模型代码

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
    }
}

RequestMessage 模型代码

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; }
    }
}

RequestMessageLogger 日志记录类代码

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;
    }
}

Program 类代码

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();

相关截图

内容的提问来源于stack exchange,提问作者Jacob Modiba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 07:45:24