Search code examples
.netwebapihostname

How to get the request's host name in .NET 6 Web API


I have tried with HttpContext.Request.Host.Host, but it returns the Web API's own host name not the request URI's host name. In other words I need the client's host name.

For example if I make a request from example.example.com to my APÌ located at api.api.com, HttpContext.Request.Host.Host will return "api.api.com".

Does this have something to do with my configuration or is this intended?


Solution

  • In the request headers you find two relevant properties origin and referer.

    To get the host of the a url (like referer or origin) simply feed the Uri constructor with the url: Uri uri = new Uri(url). You will find the host as a property on the uri object: uri.Host.