简体   繁体   中英

How to get the domain name/IP name in web-API?

How can I get the (ipName:PortNumber) mentioned in the below IP address in web-API?

https://**ipName:PortNumber**/ProductController/{productId}

We have diff servers such as: 000.00.000:8080 (ipname:portnumber), 111.11.111:8181.

I want to load these dynamically into a string as shown below.

string webServiceUrl = "https://"+ IP name +"Product Controller/{product Id}"

If you have your URI in a string, you can get the information you want as follows:

Uri uri = new Uri("https://example.com:1234/ProductController/7");
string host = uri.Host; // "example.com"
int port = uri.Port; // 1234

Inside of an ApiController , you can get the current request's URI as Request.RequestUri .

If you want to construct a URI given the host and port, you can simply do something lightweight like this:

string uri = string.Format("https://{0}:{1}/ProductController/7", host, port);

Or something a little more robust like use the UriBuilder class.

Here's how I access the Request object within a Web Api...

if (Request.Properties.ContainsKey("MS_HttpContext"))
{
     var ip = (HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.UserHostAddress;
     var host = ((HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.Url.Host;
     var port = ((HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.Url.Port;
}

Hope it helps.

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