C# 如何在web API中获取域名/IP名?

C# 如何在web API中获取域名/IP名?,c#,asp.net-web-api,asp.net-web-api2,C#,Asp.net Web Api,Asp.net Web Api2,如何在web API中获得以下IP地址中提到的(ipName:PortNumber) https://**ipName:PortNumber**/ProductController/{productId} 我们有不同的服务器,例如:000.00.000:8080(ipname:portnumber)、111.11.111:8181 我想将这些动态加载到一个字符串中,如下所示 string webServiceUrl = "https://"+ IP name +"Product Control

如何在web API中获得以下IP地址中提到的(ipName:PortNumber)

https://**ipName:PortNumber**/ProductController/{productId}
我们有不同的服务器,例如:000.00.000:8080(ipname:portnumber)、111.11.111:8181

我想将这些动态加载到一个字符串中,如下所示

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

如果您的URI为字符串,则可以按如下方式获取所需信息:

Uri uri = new Uri("https://example.com:1234/ProductController/7");
string host = uri.Host; // "example.com"
int port = uri.Port; // 1234
ApiController
内部,您可以将当前请求的URI作为
request.RequestUri
获取

如果要在给定主机和端口的情况下构造URI,只需执行如下轻量级操作:

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

或者一些更健壮的东西,比如使用类。

如果您的URI是字符串,您可以按如下方式获得所需的信息:

Uri uri = new Uri("https://example.com:1234/ProductController/7");
string host = uri.Host; // "example.com"
int port = uri.Port; // 1234
ApiController
内部,您可以将当前请求的URI作为
request.RequestUri
获取

如果要在给定主机和端口的情况下构造URI,只需执行如下轻量级操作:

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

或者一些更健壮的东西,比如使用类。

下面是我如何在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;
}

希望能有所帮助。

以下是我如何在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;
}

希望有帮助。

Uri.Authority
将是一个更好的选择,因为它为您处理默认端口。@user3629247您必须更好地解释自己。人们需要知道你想回答什么,而不是你不想回答什么。
Uri.Authority
会是一个更好的选择,因为它为你处理默认端口。@user3629247你必须更好地解释自己。人们需要知道你想回答什么,而不是你不想回答什么。这个答案更适合我们的需要(因为我们不知道out uri是什么)。这个答案更适合我们的需要(因为我们不知道out uri是什么。)