【CSharp】WebApi日志记录

   |   1 minute read   |   Using 126 words

WebApi日志记录

  • 在某些系统中,需要记录每个 request 的 日志
  • 在 asp.net 中 我们可以通过原生的 HttpContext 进行获取

代码

        var remoteIpAddress = HttpContext.Connection.RemoteIpAddress;
        var userAgent = HttpContext.Request.Headers["User-Agent"].ToString();
        var requestPath = HttpContext.Request.Path.Value;
        
        Console.WriteLine("-------------------------");
        Console.WriteLine(remoteIpAddress);
        Console.WriteLine(userAgent );
        Console.WriteLine(requestPath );
        Console.WriteLine("-------------------------");
  • remoteIpAddress: 访问程序的机器
  • userAgent: 可以获取 操作系统 浏览器 信息
  • requestPath: 在 baseurl 下的路径

输出

-------------------------
127.0.0.1                                                                                                      
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36
/WeatherForecast
-------------------------

测试

  • 如果我们想在局域网内用其他测试,会发现访问不了
  • 可以在 Program.cs 添加如下代码,使得所有人可以访问

    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();
    
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
    app.UseSwagger();
    app.UseSwaggerUI();
    }
    
    // ***********************************************
    // Listen on all network interfaces on port 5137
    // change the port as you need
    // ***********************************************
    app.Urls.Add("http://0.0.0.0:5137");
        
    app.UseHttpsRedirection();
    
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();
    
    


© 2025 by clayliu. All Rights Reserved.