20:07 0 0
Know domain name from StartUp in MVC

Know domain name from StartUp in MVC

  DrUalcman |  mayo 142022
 Español English

Algunas veces cuando tenemos una página web que aloja varios dominios, y dependiendo del dominio, la web se debe de comportar de forma diferente, es posible que cuando la aplicación va iniciarse, debas de conocer que dominio es el que esta en uso cuando se hace la injección de algún servicio cuando se está injectando en el contenedor de dependencias.

Pongamonos en contexto

Bueno, por lo menos esto me ha ocurrido a mi con un projecto multi empresa, donde dependiendo del dominio la base de datos selecciona diferentes registros. El problema lo encontré  cuando estaba realizando la injección de los clientes Api, que su dirección base debería ser igual al dominio que estaba en uso en el momento de hacer la injección. Entonces desde el fichero Startup.cs dentro del método ConfigureServices no se puede tener acceso, todabía, al contexto para saber el dominio que se está usando.

Cuando estaba en modo de desarrollo, no se apreció el problema, ya que el dominio siempre es localhost y claro, se podría hacer una simple variable string que contuviera el texto localhost y todo funciona. Pero en producción no se podía, por lo que hubo que buscar una solución un poco "más profesional".

La solución, como pequeño truco.

Tras investigar un poco, y sin encontrar una solución, me fuí a dar un paseo y ví la luz al final del tunel. Como siempre suele pasar, cuando descansas un poco al estar bloqueado las soluciones se vienen solas. Y lo que se me ocurrió para resolver el problema fué lo siguiente.

1. Agregar al contenedor de dependencias el HttpContextAccessor
2. Crear una clase que recibe una instancia de IHttpContextAccessor llamada WebDomainHelper 
3. En el archivo Startup.cs declarar una variale del tipo WebDomainHelper llamada DomainHelper por ejemplo
4. Seguimos en el archivo Startup.cs y en el método Configure instanciamos nuestra varialbe DomainHelper pasando como parámetro el IHttpContextAccessor al cual tenemos acceso desde app.AplicationiServices.GetRequiredService()
5. Ahora buscamos las líneas donde estamos injectando nuestro HttpClient y en su BaseAddress podremos usar nuestro método DomainHelper.GetDomain()

Ejemplo de código

En este pequeño ejemplo puedes se muestra como inicialilzar la web y la clase helper que vamos a utilizar.

Sometimes when we have a web page that hosts several domains, and depending on the domain, the web must behave differently, it is possible that when the application is going to start, it must know which domain is in use when it is done. the injection of some service when it is being injected into the dependency container.

Let's get in context

Well, at least this has happened to me with a multi-company project, where depending on the domain, the database selects different records. I found the problem when I was injecting the Api clients, that their base address should be equal to the domain that was in use at the time of injection. So from the Startup.cs file within the ConfigureServices method, it is still not possible to have access to the context to know the domain that is being used.

When I was in development mode, I didn't notice the problem, since the domain is always localhost and of course, you could just make a simple variable string containing the text localhost and everything would work. But in production it was not possible, so a slightly "more professional" solution had to be found.

The solution, as a little trick.

After doing some research, and without finding a solution, I went for a walk and saw the light at the end of the tunnel. As always happens, when you rest a little while being blocked, the solutions come by themselves. And what I came up with to solve the problem was the following.

1. Add the HttpContextAccessor to the dependency container
2. Create a class that receives an instance of IHttpContextAccessor called WebDomainHelper
3. In the Startup.cs file declare a variable of type WebDomainHelper called DomainHelper for example.
4. We continue in the Startup.cs file and in the Configure method we instantiate our DomainHelper varialbe passing the IHttpContextAccessor as a parameter to which we have access from app.AplicationiServices.GetRequiredService()
5. Now we look for the lines where we are injecting our HttpClient and in its BaseAddress we can use our DomainHelper.GetDomain() method.

Code example

In this small example you can show how to initialize the web and the helper class that we are going to use.


    public class Startup
{
public IConfiguration Configuration { get; }
private WebDomainHelper DomainHelper;

public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddScoped(sp => new HttpClient() { BaseAddress = new Uri(DomainHelper.GetDomain()) });
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
DomainHelper = new WebDomainHelper(app.ApplicationServices.GetRequiredService());

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(
endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Account}/{action=Index}/{id?}");
}
);
}
}



public class WebDomainHelper
{
IHttpContextAccessor ContextAccessor;
public WebDomainHelper(IHttpContextAccessor contextAccessor)
{
ContextAccessor = contextAccessor;
}

///
/// Get domain name
///

public string GetDomain()
{
string serverURL;
try
{
serverURL = $"{ContextAccessor.HttpContext.Request.Scheme}://{ContextAccessor.HttpContext.Request.Host.Value}/";
}
catch
{
serverURL = string.Empty;
}
return serverURL;
}
}



0 Comentarios

 
 
 

Archivo