v7.3.2018.0614   重构高性能资源池,减少GC压力,增加线程池,让异步任务得到平等竞争CPU的机会
大石头 authored at 2018-06-14 17:56:44
1.31 KiB
X
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace NewLife.Web
{
    /// <summary>Http上下文</summary>
    public static class HttpContext
    {
        private static IHttpContextAccessor _accessor;

        /// <summary>当前Http上下文</summary>
        public static Microsoft.AspNetCore.Http.HttpContext Current => _accessor.HttpContext;

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

    /// <summary>Http上下文扩展</summary>
    public static class StaticHttpContextExtensions
    {
        /// <summary>添加Http上下文访问器</summary>
        /// <param name="services"></param>
        public static void AddHttpContextAccessor(this IServiceCollection services) => services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        /// <summary>配置静态Http上下文访问器</summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app)
        {
            var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            HttpContext.Configure(httpContextAccessor);
            return app;
        }
    }
}