因接口版本升级 并使用core 6.0 却发现HttpContext.Current.Request 用不了 所以在网上找了半天 说是使用Microsoft.AspNetCore.Http.IHttpContextAccessor
private IHttpContextAccessor _httpContextAccessor; public WebHelper(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public string GetIpAddress() { var httpContext = _httpContextAccessor.HttpContext; var ip = httpContext.Request.Headers["X-Forwarded-For"].ToString().Split(',')[0].Trim(); if (string.IsNullOrEmpty(ip)) { ip = httpContext.Connection.RemoteIpAddress.ToString(); } return ip; }
上面这个是用的地方 在调用接口的时候却一直报错 本来以为是依赖注入的问题 后查询是使用这个需要在Program注册
var builder = WebApplication.CreateBuilder(args); //使用IHttpContextAccessor 必须注入 builder.Services.AddHttpContextAccessor();
或者
var builder = WebApplication.CreateBuilder(args); builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
标签:webapi,Core,httpContextAccessor,IHttpContextAccessor,ip,builder,报错,var From: https://www.cnblogs.com/wuyabaibsd/p/17839022.html