Reputation: 317
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}"
Upvotes: 1
Views: 7808
Reputation: 6992
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.
Upvotes: 2
Reputation: 79601
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.
Upvotes: 3