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

Time:09-12

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?

CodePudding user response:

You can get the connection information using:

HttpContext.Request.HttpContext.Connection

And specifically the IP address with this:

HttpContext.Request.HttpContext.Connection.RemoteIpAddress

Connection Info documentation: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.connectioninfo?view=aspnetcore-6.0

CodePudding user response:

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.

  • Related