netcore HttpContext 自定义请求上下文内容

 

   public static class HttpContext
    {
        private static IHttpContextAccessor _accessor;

        public static Microsoft.AspNetCore.Http.HttpContext Current => _accessor.HttpContext;

        internal static void Configure(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
    }

    public static class StaticHttpContextExtensions
    {
        public static void AddCustomHttpContextAccessor(this IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

        public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app)
        {
            var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            HttpContext.Configure(httpContextAccessor);
            return app;
        }
    }

 

注册服务:

 public void ConfigureServices(IServiceCollection services)
{
           services.AddHttpContextAccessor();
            services.AddCustomHttpContextAccessor();
}

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
            
          app.UseStaticHttpContext();
 }

 

posted @ 2020-05-19 23:43  wfpanskxin  阅读(773)  评论(0编辑  收藏  举报