Peter
Peter

Reputation: 2261

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.

Upvotes: 1

Views: 4435

Answers (1)

Geoffrey Fook
Geoffrey Fook

Reputation: 716

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

Upvotes: 2

Related Questions