How can I pass absolute url from WebApi to UI layer RRS feed

  • Question

  • User1001065250 posted

    I have an application with an application to pass absolute url from WebApi to UI layer. The problem is the url is different for each environment (dev, test, prod) so I can't just hardcode it. I could grab the value from each environments database but would like to avoid that. My question is there a Asp.net Core style way to do using Startup.cs and DI? Any other tricks I am missing?

    Friday, January 31, 2020 5:47 PM

All replies

  • User475983607 posted

    You can fetch the host header.

        public class HomeController : Controller
            private readonly ILogger<HomeController> _logger;
            private readonly IWebHostEnvironment _env;
            private IHttpContextAccessor _httpacc;
            public HomeController(ILogger<HomeController> logger, 
                IWebHostEnvironment env, 
                IHttpContextAccessor httpacc)
                _logger = logger;
                _env = env;
                _httpacc = httpacc;
            public ActionResult Index()
                string host = _httpacc.HttpContext.Request.Host.Value;
                return Content(host);


    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    It's a bit unusual that the WebApi needs to pass the URL to the UI because the UI is the source of the request.  If you are referring to REST patterns where you return the URL of a newly created resource then see the official docs.


    return CreatedAtAction(nameof(GetById), new { id = product.Id }, product); 

    Friday, January 31, 2020 6:18 PM
  • User711641945 posted

    Hi mrburnttoast79,

    I have an application with an application to pass absolute url from WebApi to UI layer.

    What is your detailed scenario to pass absolute url to the UI?

    You could get the url like below:

    var absUrl = string.Format("{0}://{1}{2}", Request.Scheme,Request.Host, "/Home/Index");             

    Or you could display the absolute url directly in UI like below:

    @Url.Action("Index", "Home", null, this.Context.Request.Scheme);

    Best Regards,


    Monday, February 3, 2020 11:05 AM