2

I have an application that is written on the top of ASP.NET Core 2.2 framework. I need to create JSON-Ld data which requires a full URL. The object that I want to convert to JSON-Ld is generated using a service class. Within my service class, I want to be able to create the full URL.

I tried to create the URLs using the LinkGenerator class after injecting it into the construction of my service class. However, the LinkGenerator generates relevant URI, not the fully qualified URL (excluding the domain).

I also tried to create an instance of UrlHelper hoping I can use it to generate fully qualified URLs. After injecting IHttpContextAccessor into the service contractor, I tried to create an instance of UrlHelper like so

var httpContextBase = new HttpContextWrapper(HttpContextAccessor.HttpContext);
var urlHelper = new UrlHelper(httpContextBase);

However, new UrlHelper(httpContextBase) throws the following exception

System.NullReferenceException: 'Object reference not set to an instance of an object.'

How can I correctly generate fully qualified URLs from a service class?

Junior
  • 11,602
  • 27
  • 106
  • 212
  • A "fully qualified URL", by definition, includes the domain. It is usually referred to as an "absolute URL" in web standard documents though: https://stackoverflow.com/q/17406848/215552 – Heretic Monkey Jun 11 '19 at 23:34

1 Answers1

4

I found one way to do it using LinkGenerator

I injected IHttpContextAccessor and LinkGenerator in the constructor of my service class. Then I generated the full URI like so

var url = LinkGenerator.GetUriByAction("index", "home", null, HttpContextAccessor.HttpContext.Request.Scheme, HttpContextAccessor.HttpContext.Request.Host);
Junior
  • 11,602
  • 27
  • 106
  • 212