asp.net core中IHttpContextAccessor和HttpContextAccessor的妙用

我们现代的HttpContext.Current将依赖于从IHttpContextAccessor解析上下文,并且可能如下所示:

namespace System.Web
{
    public static class HttpContext
    {
        private static IHttpContextAccessor _contextAccessor;
 
 
        public static Microsoft.AspNetCore.Http.HttpContext Current => _contextAccessor.HttpContext;
 
 
        internal static void Configure(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
    }
}

请注意,我们甚至将它放置在System.Web命名空间中,以便您进行任何潜在的迁移更容易一些。

我们只需要在处理流水线中尽可能早地将代码添加到Configure中,并传入IHttpContextAccessor。这可以通过两种扩展方法来实现:

public static class StaticHttpContextExtensions
    {
        public static void AddHttpContextAccessor(this IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }
 
 
        public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app)
        {
            var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            Common.HttpContext.Configure(httpContextAccessor);
            return app;
        }
 

第一个将在启动时从ConfigureServices中调用,并在DI中注册访问器。我们已经确定,这是默认IHttpContextFactory正确分享其HttpContext实例所必需的。

第二个将在启动时从Configure中调用,并且它将确保我们的自定义HttpContext.Current被赋予其IHttpContextAccessor以使其可以正常工作。

就是这样 这是我的Startup类,为静态HttpContext.Current设置表。

public class Startup
    {
        public void ConfigureServices(IServiceCollectionservices)
        {
            services.AddHttpContextAccessor();
        }
 
        public void Configure(IApplicationBuilderapp)
        {
            app.UseStaticHttpContext();
            app.UseMvc();
        }
    }

例子:
public class MyService {

public void DoWork() {
var context=HttpContext.Current; // continue with context instance
} }
 

asp.net core中IHttpContextAccessor和HttpContextAccessor的妙用

上一篇:mysql8.0.忘记root密码


下一篇:postgres 删除数据库连接