'Get base URL of webapi

(typing from mobile) I got a webapi with an action based http controller. So there are no web pages just API. vsstudio generates localhost:port URLs when deployed localhost. I wonder how to get the base URL even if it's deployed elsewhere. There must be some environment var I guess.



Solution 1:[1]

You can get the base URL from the HTTPContext. I wrote some sample code for you, hope it helps!

[Route("api")]
public class MyController : ControllerBase
{
    [HttpGet]
    [Route("getBaseUrl")]
    public string GetBaseUrl()
    {
        var request = HttpContext.Request;

        var baseUrl = $"{request.Scheme}://{request.Host}:{request.PathBase.ToUriComponent()}";

        return baseUrl;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Geoffrey Fook