ASP.NET Core Web API,如何在启动类中访问 HttpContext

vid*_*rga 4 c# api .net-core asp.net-core

我正在尝试访问HttpContextgetRemoteIpAddressUser-Agent,但在 Startup.cs 内。

 public class Startup
        {
            public Startup(IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
            {
                Configuration = configuration;
                _httpContextAccessor = httpContextAccessor;
            }

            public IConfiguration Configuration { get; }
            public IHttpContextAccessor _httpContextAccessor { get; }

            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                IdentityModelEventSource.ShowPII = true;

                var key = Encoding.ASCII.GetBytes(Configuration.GetValue<string>("claveEncriptacion"));
                var ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
                var userAgent = _httpContextAccessor.HttpContext.Request.Headers["User-Agent"].ToString();

services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                //x.Audience = ip + "-" + userAgent;
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = true
                };
            });
Run Code Online (Sandbox Code Playgroud)

使用前面的代码,我在执行项目时出错。

Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'JobSiteMentorCore.Startup'.'
Run Code Online (Sandbox Code Playgroud)

Tan*_*jel 9

根据ASP.NET Core 文档Startup,使用 Generic Host (IHostBuilder) 时,只能将以下服务类型注入到构造函数中:

IWebHostEnvironment
IHostEnvironment
IConfiguration
Run Code Online (Sandbox Code Playgroud)

所以你不能注入IHttpContextAccessor构造Startup函数。

但是,您可以在类ConfigureServices的方法中获得 DI 解析服务Startup,如下所示:

public void ConfigureServices(IServiceCollection services)
{

    services.AddScoped<IYourService, YourService>();

    // Build an intermediate service provider
    var serviceProvider = services.BuildServiceProvider();

    // Resolve the services from the service provider
    var yourService = serviceProvider.GetService<IYourService>();

}
Run Code Online (Sandbox Code Playgroud)

但是你不能得到类似的HttpContext使用IHttpContextAccessor,因为HttpContext除非在任何期间执行的代码为空,否则你不能得到类似的使用HttpRequest因此,您必须从类的任何自定义方法middleware中执行所需的操作,如下所示:ConfigureStartup

public class YourCustomMiddleMiddleware
{
    private readonly RequestDelegate _requestDelegate;

    public YourCustomMiddleMiddleware(RequestDelegate requestDelegate)
    {
        _requestDelegate = requestDelegate;
    }

    public async Task Invoke(HttpContext context)
    {

      // Your HttpContext related task is in here.

      await _requestDelegate(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在类Configure的方法中Startup如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   app.UseMiddleware(typeof(YourCustomMiddleMiddleware));
}
Run Code Online (Sandbox Code Playgroud)