.net core 对 HttpContext 类的扩展

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Sheepsoft.Core.Context
{
    ///


    /// 上下文 HttpContext 类
    ///

    public static class HttpContextSheep
    {
        #region 帮助
        private static IHttpContextAccessor _contextAccessor;

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

        public static void Configure(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
        #endregion

        #region  注册服务
        public static void AddHttpContextAccessor(this IServiceCollection services)
        {
            services.AddSingleton();
        }

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

        #endregion
    }
}
/**
 使用方法
在 Startup 下

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseStaticHttpContext();
}
**/

你可能感兴趣的:(.net,core)