Last post Jul 05, 2018 09:45 AM by Xing Zou
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.