Search code examples
c#asp.net-mvc-5webapi

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

  • 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;
        }
    }