Last post Oct 05, 2018 01:35 AM by Gfw
Jul 04, 2018 07:26 AM|haraldsh|LINK
In one of my libraries I need to get the current url from HttpContext in ASP.NET Core.
The only suggestions I find uses dependency injection to retrieve the current httpcontext, which I'm not sure how to solve in a library project.
The reason why I need the url, is because the class that logs exceptions also has to have current url along with the request.
The tip I found proposes using System.Net.Http nuget package to solve the issue. However, I'm not finding any examples of how to use this library.
How can I use the System.Net.Http nuget package to find the current httpcontext?
Trying out this tactic:
Jul 04, 2018 02:55 PM|maherjendoubi|LINK
Microsoft Team recommends using DI to access the HttpContext.Current.
Jul 04, 2018 11:07 PM|lextm|LINK
I'm not sure how to solve in a library project.
Rewrite your library to ask the caller for HttpContext object, so you don't need to query it yourself.
Jul 05, 2018 09:45 AM|Xing Zou|LINK
In order to get current Url from HttpContext in the library project, I recommend that you could pass the IHttpContextAccessor instance in your web project into the library class as lextm suggested.
You could refer the demo to get url in your library:
1. In library class, add a function to get url.
public class UrlClass
public string showURL(IHttpContextAccessor httpcontextaccessor)
var request = httpcontextaccessor.HttpContext.Request;
var absoluteUri = string.Concat(
You need to add namespace of Microsoft.AspNetCore.Http and assembly of
2. In your web project, inject HttpContextAccessor in ConfigureServices.
public void ConfigureServices(IServiceCollection services)
public class HomeController : Controller
private readonly IHttpContextAccessor _httpContextAccessor;
public HomeController(IHttpContextAccessor httpContextAccessor)
_httpContextAccessor = httpContextAccessor;
3. Create an instance of library class in web project and invoke the showURL method to test.
In above controller ,add namespace of library and then add below code to an action:
UrlClass url = new UrlClass();
string result = url.showURL(_httpContextAccessor);
The string “result” represents the value of current url. It means that you could get current url in the library project.
Oct 04, 2018 06:56 PM|Gfw|LINK
I needed access to some session variables in a library. I did a lot of searching and found a somewhat simple approach. I needed to get the current logged in user from a session variable in the web app for an EF Core audit trail. I am using .net core 2.1
and it does work (at least for me). Hope this helps.
public class GetAuditName
public HttpContext Current => new HttpContextAccessor().HttpContext;
public string DoIt()
return = Current.Session.GetString("AuditName");
Oct 05, 2018 12:21 AM|bruce (sqlwork.com)|LINK
Oct 05, 2018 01:35 AM|Gfw|LINK
Can you suggest a better alternative? It may not be the best, but it is the only way that I have found.