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.
Related
I want Separating a part of the current URL
Example:localhost:50981/Admin/AddCustomer.aspx
The part I want: AddCustomer
or
Example:localhost:50981/Request/Customer.aspx
The part I want: Customer
You can use AbsolutePath in your onLoad function of page.
//AddCustomer or Customer
string yourPath = HttpContext.Current.Request.Url.AbsolutePath.Split('/').Last().Split('.')[0];
You can make use of string.Split():
var url = "localhost:50981/Admin/AddCustomer.aspx";
var result = url.Split('/').Last().Split('.')[0];
To get the current Url path in Asp.Net:
var url = HttpContext.Current.Request.Url.AbsolutePath;
Note:
If you are interested in how to get the different parts of an url have a look at this answer:
var scheme = Request.Url.Scheme; // will get http, https, etc.
var host = Request.Url.Host; // will get www.mywebsite.com
var port = Request.Url.Port; // will get the port
var path = Request.Url.AbsolutePath; // should get the /pages/page1.aspx part, can't remember if it only get pages/page1.aspx
I am supporting a system that needs to get the client's computer name I try different codes but all of them just get the computer name of the host server, not the client's computer name. Here's the snippet:
public void CreateEvents(string className, string eventName, string eventData, string userId)
{
string hostName = Dns.GetHostName(); // Retrive the Name of HOST
string compname= HttpContext.Current.Request.UserHostAddress;
var browser = HttpContext.Current.Request.Browser.Browser + " " + HttpContext.Current.Request.Browser.Version;
if (string.IsNullOrEmpty(userId))
{
userId = compname;
}
var entity = new EventLog
{
ClassName = className,
EventName = eventName,
EventData = eventData,
IpAddress = ipAddress,
Browser = browser,
UserId = userId,
CreatedDate = DateTime.Now
};
_db.EventLogs.Add(entity);
_db.SaveChanges();
}
public string GetIpAddress()
{
HttpContext context = System.Web.HttpContext.Current;
string compname= context.Request.UserHostAddress; //System.Net.Dns.GetHostName();
return compname;
}
Thanks in advance!
No you can't, unless the client sends such info when making HTTP requests. By "client", I'm referring to any - some app, browser, etc.
You can inspect your own browser request flow using standard browser dev tools and see exactly what info your browser is sending. It will not have your machine name (unless something in your machine is and that would likely be a problem).
That said, HTTP Header data is what you have aside from standard network info such as IP address (which also isn't guaranteed to be the client's IP address - it could be the client's network address). The closest you can get to is hostname if it exists, and even then, just like IP address, is not guaranteed to be machine name.
A possible exception would be in an internal network (LAN).
you can use
HttpContext.Request.UserHostAddress
for getting the IP address, also Request has UserHostName but I am not sure about this property
You can get computer name as follows:
Environment.MachineName.ToString()
You can get hosting server name as follows:
Server.MachineName.ToString()
Trying to get the public address(not local IP) of the machine using c#. Unable to get Public IP.
We can get public IP Address using external libraries or API like in this link.
Is there any possible to get machine pubic IP address in c# without using external API and libraries?
Try this
public String getPublicIp()
{
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3=a2.Split('<');
string ip = a3[0];
return ip;
}
Retrieve public IP (V4) address, asynchronously (recommended)
HttpClient client = new HttpClient();
var ipTask = client.GetStringAsync("https://api.ipify.org");
var ipAddress = await ipTask;
For IP V6, use this URL:
var ipTask = client.GetStringAsync("https://api6.ipify.org");
Based on below pic, there may be several WebSite on IIS with several services,
So the only thing which I have separate them from together is Hostname , in the other site sibling services may call together so I have decided to change hostname if they are not on localhost so in service I tried something like this:
HostName = OperationContext.Current.Channel.LocalAddress.Uri.Host.ToString();
and in service when I am calling another service by it's proxy I Rehome
public void ReHome(string hostName)
{
if (!string.IsNullOrEmpty(hostName))
{
if (this.Endpoint.Address.Uri.DnsSafeHost.ToLower().Equals("localhost"))
{
string newAddress = string.Format("{0}://{1}{2}/{3}", Endpoint.Address.Uri.Scheme
, hostName, string.IsNullOrEmpty(Endpoint.Address.Uri.Port.ToString()) ? string.Empty : ":" + Endpoint.Address.Uri.Port.ToString()
, Endpoint.Address.Uri.AbsolutePath);
this.Endpoint.Address = new EndpointAddress(newAddress);
}
}
}
call example in a service:
using (var hisProxy = new HISIntegrationClient("hisIntegrationEndPoint", Internals.SYSTEM))
{
hisProxy.ReHome(HostName);
....
}
so is OperationContext.Current.Channel.LocalAddress.Uri.Host give me what I want that mentioned in above pic?
You get the current base address of server(hostname and port) using following code snippet
var baseAddress = OperationContext.Current.Host.BaseAddresses[0].Authority;
Are there any helper classes available in .NET to allow me to build a Url?
For example, if a user enters a string:
stackoverflow.com
and i try to pass that to an HttpWebRequest:
WebRequest.CreateHttp(url);
It will fail, because it is not a valid url (it has no prefix).
What i want is to be able to parse the partial url the user entered:
Uri uri = new Uri(url);
and then fix the missing pieces:
if (uri.Port == 0)
uri.Port = 3333;
if (uri.Scheme == "")
uri.Scheme = "https";
Does .NET have any classes that can be used to parse and manipulate Uri's?
The UriBuilder class can't do the job
The value that the user entered (e.g. stackoverflow.com:3333) is valid; i just need a class to pick it apart. i tried using the UriBuilder class:
UriBuilder uriBuilder = new UriBuilder("stackoverflow.com:3333");
unfortunately, the UriBuilder class is unable to handle URIs:
uriBuilder.Path = 3333
uriBuilder.Port = -1
uriBuidler.Scheme = stackoverflow.com
So i need a class that can understand host:port, which especially becomes important when it's not particularly http, but could be.
Bonus Chatter
Console application.
From the other question
Some examples of URL's that require parsing:
server:8088
server:8088/func1
server:8088/func1/SubFunc1
http://server
http://server/func1
http://server/func/SubFunc1
http://server:8088
http://server:8088/func1
http://server:8088/func1/SubFunc1
magnet://server
magnet://server/func1
magnet://server/func/SubFunc1
magnet://server:8088
magnet://server:8088/func1
magnet://server:8088/func1/SubFunc1
http://[2001:db8::1]
http://[2001:db8::1]:80
The format of a Url is:
foo://example.com:8042/over/there?name=ferret#nose
\_/ \_________/ \__/\_________/\__________/ \__/
| | | | | |
scheme host port path query fragment
Bonus Chatter
Just to point out again that UriBuilder does not work:
https://dotnetfiddle.net/s66kdZ
If you need to ensure that some string coming as user input is valid url you could use the Uri.TryCreate method:
Uri uri;
string someUrl = ...
if (!Uri.TryCreate(someUrl, UriKind.Absolute, out uri))
{
// the someUrl string did not contain a valid url
// inform your users about that
}
else
{
var request = WebRequest.Create(uri);
// ... safely proceed with executing the request
}
Now if on the other hand you want to be building urls in .NET there's the UriBuilder class specifically designed for that purpose. Let's take an example. Suppose you wanted to build the following url: http://example.com/path?foo=bar&baz=bazinga#some_fragment where the bar and bazinga values are coming from the user:
string foo = ... coming from user input
string baz = ... coming from user input
var uriBuilder = new UriBuilder("http://example.com/path");
var parameters = HttpUtility.ParseQueryString(string.Empty);
parameters["foo"] = foo;
parameters["baz"] = baz;
uriBuilder.Query = parameters.ToString();
uriBuilder.Fragment = "some_fragment";
Uri finalUrl = uriBuilder.Uri;
var request = WebRequest.Create(finalUrl);
... safely proceed with executing the request
You can use the UriBuilder class.
var builder = new UriBuilder(url);
builder.Port = 3333
builder.Scheme = "https";
var result = builder.Uri;
To be valid a URI needs to have the scheme component. "server:8088" is not a valid URI. "http://server:8088" is. See https://www.rfc-editor.org/rfc/rfc3986