Blog

Filter posts by Category Or Tag of the Blog section!

How to get the baseurl in ASP.NET Core?

Sunday, 22 November 2020

In order to get the base URL in controller scope, you simply get via Request:
 

public class HomeController : ControllerBase

   {

       public IActionResult About()

       {

           var url =$"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";

           return Ok();

       }

   }


 

But for using it everywhere, you need to create an extension for httpContext:

 

public class HttpContextExtension

   {

       private static IHttpContextAccessor httpContextAccessor;



       public static HttpContext Current => httpContextAccessor.HttpContext;



       public static string AppBaseUrl => $"{Current.Request.Scheme}://{Current.Request.Host}{Current.Request.PathBase}";



       internal static void Configure(IHttpContextAccessor contextAccessor)

       {

           httpContextAccessor = contextAccessor;

       }

   }



   public static class HttpContextExtensions

   {

       public static void AddHttpContextAccessor(this IServiceCollection services)

       {

           services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

       }



       public static IApplicationBuilder UseHttpContext(this IApplicationBuilder app)

       {

           HttpContextExtension.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());

           return app;

       }

   }



 

And don’t forget to add the UseHttpContext() in the startup class:

 

app.UseHttpContext()




Now you can use it everywhere:
 

var appBaseUrl = HttpContextExtension.AppBaseUrl;



 

Category: Software

Tags: Asp.Net

comments powered by Disqus