简体   繁体   English

如何从服务层获取 HttpContext

[英]How to get HttpContext from service layer

I have requirement to add in a header on each request to a service a header MyHeader.我需要在对服务的每个请求中添加 header header MyHeader。 MyHeader is the jwt I have received when the user is logging on. MyHeader是用户登录时收到的jwt。

I tried to read it from HttpContext.Request.Headers.我试图从 HttpContext.Request.Headers 中读取它。 I am trying to access it in my service.我正在尝试在我的服务中访问它。 I could get the result in the controller but not on the Service layer.我可以在 controller 中得到结果,但不能在服务层上得到结果。 Can anyone help me to get the same on service class.任何人都可以帮助我在服务 class 上得到同样的结果。

I'm using Asp.net core我正在使用 Asp.net 内核

In Startup#ConfigureServices:在 Startup#ConfigureServices 中:

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

In your service class:为您服务 class:

public class YourServiceClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    ...

    // constructor
    public YourServiceClass(IHttpContextAccessor httpContextAccessor, ...)
    {
      _httpContextAccessor = httpContextAccessor;
      ...
    }

    public void YourServiceMethod() 
    {
      var headers = _httpContextAccessor.HttpContext.Request.Headers;
      ...
    }

    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM