It is possible to retrieve host address in application service in abp framework?

2.2k views Asked by At

It is possible to have host address in app services?

For example we want send email to customer with specific link point to site address. How is this possible?

2

There are 2 answers

4
Alper Ebicoglu On BEST ANSWER

HttpContext.Current.Request.Url

can get you all the info on the URL. And can break down the url into its fragments.

0
Andrew Hodgkinson On

This came up via Google & the existing answer didn't really help. I don't necessarily agree that app services are the wrong domain for this; in ABP for example, a service is closely connected to a controller and services usually only exist in order to service web requests there. They often execute code in an authorised state that requires a signed-in user, so the whole thing is happening in the implicit domain context of an HTTP request/response cycle.

Accordingly - https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-2.2#use-httpcontext-from-custom-components

  • Add services.AddHttpContextAccessor(); to something like your Startup.cs - just after wherever you already call services.AddMvc().
  • Use dependency injection to get hold of an IHttpContextAccessor in your service - see below.

Using constructor-based dependency injection, we add a private instance variable to store the injected reference to the context accessor and a constructor parameter where the reference is provided. The example below has a constructor with just that one parameter, but in your code you probably already have a few in there - just add another parameter and set _httpContextAccessor inside the constructor along with whatever else you're already doing.

using HttpContext          = Microsoft.AspNetCore.Http.HttpContext;
using IHttpContextAccessor = Microsoft.AspNetCore.Http.IHttpContextAccessor;

// ...

public class SomeService : ApplicationService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public SomeService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
}

Now service code can read the HTTP context and from there things like the HTTP request's host and port.

public async Task<string> SomeServiceMethod()
{
    HttpContext context = _httpContextAccessor.HttpContext;
    string      domain  = context.Request.Host.Host.ToLowerInvariant();
    int?        port    = context.Request.Host.Port;

    // ...
}