.NET Core 获取 Request/Headers 等信息

1.在 Startup.cs 类 ConfigureServices 方法中注入  IHttpContextAccessor;

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

2.在需要使用的类的构造函数注入 IHttpContextAccessor 即可使用;

public class xxxAppService : PlatformAppService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public xxxAppService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
}

3.获取 httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();

完整代码如下:

public class xxxAppService : PlatformAppService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public xxxAppService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public async Task<string> GetHeaders()
    {
        var headers = _httpContextAccessor.HttpContext.Request.Headers;

        return headers["Authorization"];
    }
}

例如获取 Origin / Referer 信息:

var headers = _httpContextAccessor.HttpContext.Request.Headers;

var origin = headers["Origin"].FirstOrDefault().ToLowerInvariant();
var referer = headers["Referer"].FirstOrDefault().ToLowerInvariant();

凡是总有例外的时候,比如有的场景其实是不能通过注入的方式来实例化 IHttpContextAccessor,下面我们就来处理这种场景。

例如在 Startup 中因为还没有触发请求,所以这时因为各种业务需要 IHttpContextAccessor 就有尴尬了。下面场景是在使用 WebApiClient 中。

背景介绍:提供接口供第三方调用,而接口中其实不做数据处理(暂时),只做转发并且需要将 Header 信息一并转发,其实就是实现了一次透传,而在 ApiActionFilterAttribute 类从 Startup 初始化时就不能获取到 IHttpContextAccessor,这是就需要通过控制反转的方式在被调用时再按需实例化。

public class ThirdPartyJianweiHttpRegistrarHeaderAttribute : ApiActionFilterAttribute
{
    private readonly IConfigurationRoot _appConfiguration;

    public ThirdPartyJianweiHttpRegistrarHeaderAttribute(IConfigurationRoot appConfiguration)
    {
        _appConfiguration = appConfiguration;
    }

    public override async Task OnBeginRequestAsync(ApiActionContext context)
    {
        //从请求中获取 Header 并注入 WebApiClient Header 中传递
        var request = context.GetService<IHttpContextAccessor>().HttpContext.Request;
        if (request != null)
        {
            var headers = request.Headers;
            if (headers != null)
            {
                var keyId = headers["keyId"].FirstOrDefault();
                var code = headers["rCode"].FirstOrDefault();
                context.RequestMessage.Headers.Add("keyId", keyId);
                context.RequestMessage.Headers.Add("ts", headers["ts"].FirstOrDefault());
                context.RequestMessage.Headers.Add("rCode", code);
                context.RequestMessage.Headers.Add("signature", headers["signature"].FirstOrDefault());
            }
        }
        await base.OnBeginRequestAsync(context);
    }

    public override Task OnEndRequestAsync(ApiActionContext context)
    {
        return base.OnEndRequestAsync(context);
    }
}

代码中 context.GetService<IHttpContextAccessor> 实现了 IHttpContextAccessor 实例化。

posted @ 2019-06-11 11:15  Jöhan  阅读(1609)  评论(0编辑  收藏  举报