If you need this somewhere in your application, you should create middleware. Define your static class and extension method to add middleware to the service pipeline like this.
public class MyHttpContext { private static IHttpContextAccessor m_httpContextAccessor; public static HttpContext Current => m_httpContextAccessor.HttpContext; public static string AppBaseUrl => $"{Current.Request.Scheme}://{Current.Request.Host}{Current.Request.PathBase}"; internal static void Configure(IHttpContextAccessor contextAccessor) { m_httpContextAccessor = contextAccessor; } } public static class HttpContextExtensions { public static void AddHttpContextAccessor(this IServiceCollection services) { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); } public static IApplicationBuilder UseHttpContext(this IApplicationBuilder app) { MyHttpContext.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>()); return app; } }
In this case, it may be a bit redundant to expose the HttpContext, but I find it very useful.
Then you add it to the pipeline in your Configfure method, which is located in Startup.cs.
app.UseHttpContext()
From there, just use it anywhere in your code.
var appBaseUrl = MyHttpContext.AppBaseUrl;
source share