简体   繁体   中英

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?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM