【问题标题】:Accessing HttpContext in ASP.NET Core 2.2 Class library [duplicate]在 ASP.NET Core 2.2 类库中访问 HttpContext [重复]
【发布时间】:2019-01-14 22:38:31
【问题描述】:

我需要在 ASP.NET Core 2.2 的类库中访问HttpContext.Current

HttpContext.Current.Request.Url.ToString().Contains("SAMLart")

当我尝试仅尝试使用 HomeController 中的方法时,我正在尝试移植代码,而 HttpContext 在主 Web 项目中甚至没有 Current

【问题讨论】:

  • 您找到解决方案了吗?我也在类库中面临这个问题

标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.0 httpcontext


【解决方案1】:

Startup 类中注册IHttpContextAccessor,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Or you can also register as follows

    services.AddHttpContextAccessor();
}

然后在你的类库中

public class Test 
{
    private IHttpContextAccessor _httpContextAccessor;
    public Test(IHttpContextAccessor httpContextAccessor)
    {
         _httpContextAccessor = httpContextAccessor;
    }
    public void Foo()
    {
        _httpContextAccessor.HttpContext.Request.Path..
    }
}

【讨论】:

  • 嗯,我确实有一个类库 - 所以在类库中没有启动...想法?
猜你喜欢
  • 2017-09-17
  • 2011-08-23
  • 2015-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多