Currently i am using this code to get the above :
Uri baseUri = new Uri(url);
Uri myUri = new Uri(baseUri, strRef);
domain = baseUri.Host;
Console.WriteLine(myUri.ToString());
strRef = myUri.ToString();
if (strRef.Contains(domain))
{
//THIS MEANS IT BELONGS TO SAME DOMAIN...
}
But using this code i am having some issue like suppose we have a main url = http://www.xxx.co.uk
Then the above code also treats a url like http://www.news.xxx.co.uk as external link ? Is this correct should it do that if not any one know a better solution for this?
I think you are in the correct path. But, to grab the latter mentioned URL (http://www.news.xxx.co.uk/) you could do a quick fix like this.
domain = baseUri.Host.Replace("www.", string.Empty);
Cheers!
vote if helpful.
Related
I want to get the current domain name in asp.net c#.
I am using this code.
string DomainName = HttpContext.Current.Request.Url.Host;
My URL is localhost:5858but it's returning only localhost.
Now, I am using my project in localhost. I want to get localhost:5858.
For another example, when I am using this domain
www.somedomainname.com
I want to get somedomainname.com
Please give me an idea how to get the current domain name.
Try getting the “left part” of the url, like this:
string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
This will give you either http://localhost:5858 or https://www.somedomainname.com whether you're on local or production. If you want to drop the www part, you should configure IIS to do so, but that's another topic.
Do note that the resulting URL will not have a trailing slash.
Using Request.Url.Host is appropriate - it's how you retrieve the value of the HTTP Host: header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.
Note that localhost:5858 is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority.
Furthermore, it is not valid to get somedomain.com from www.somedomain.com because a webserver could be configured to serve a different site for www.somedomain.com compared to somedomain.com, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.') works in a pinch.
Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config) is a red-herring.
Here is a screenshot of Request.RequestUri and all its properties for everyone's reference.
You can try the following code :
Request.Url.Host +
(Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)
I use it like this in asp.net core 3.1
var url =Request.Scheme+"://"+ Request.Host.Value;
www.somedomain.com is the domain/host. The subdomain is an important part. www. is often used interchangeably with not having one, but that has to be set up as a rule (even if it's set by default) because they are not equivalent. Think of another subdomain, like mx.. That probably has a different target than www..
Given that, I'd advise not doing this sort of thing. That said, since you're asking I imagine you have a good reason.
Personally, I'd suggest special-casing www. for this.
string host = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);;
if (host.StartsWith("www."))
return host.Substring(4);
else
return host;
Otherwise, if you're really 100% sure that you want to chop off any subdomain, you'll need something a tad more complicated.
string host = ...;
int lastDot = host.LastIndexOf('.');
int secondToLastDot = host.Substring(0, lastDot).LastIndexOf('.');
if (secondToLastDot > -1)
return host.Substring(secondToLastDot + 1);
else
return host;
Getting the port is just like other people have said.
HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use
HttpContext.Current.Request.Url.Port
the Request.ServerVariables object works for me. I don't know of any reason not to use it.
ServerVariables["SERVER_NAME"] and ServerVariables["HTTP_URL"] should get what you're looking for
You can try the following code to get fully qualified domain name:
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
Here is a quick easy way to just get the name of the url.
var urlHost = HttpContext.Current.Request.Url.Host;
var xUrlHost = urlHost.Split('.');
foreach(var thing in xUrlHost)
{
if(thing != "www" && thing != "com")
{
urlHost = thing;
}
}
To get base URL in MVC even with subdomain www.somedomain.com/subdomain:
var url = $"{Request.Url.GetLeftPart(UriPartial.Authority)}{Url.Content("~/")}";
string domainName = HttpContext.Request.Host.Value;
this line should solve it
Try this:
#Request.Url.GetLeftPart(UriPartial.Authority)
I have an MVC application and I am going through a strange situation right now.
I am allowing users to stare and Display website URL's. I am using the following method to check whether the following URL is correct or not:
if(Uri.TryCreate(urlString, UriKind.Absolute, out uri))
{
// Do something
}
else
{
// Invalid Url
}
This method is not working because when I try URL starting with "www" or directly with the domain name then it does'not work.
I want the first section of If statement to be bullet proof.
Thanks for you help.
Maybe just try to create a new URI in a try-catch block.
Something like:
Uri myUri = new Uri("http://www.stackoverflow.com")
If you get to the catch then it's a wrong URL.
I'm using Selenium on different machines to automate testing of a MVC Web application.
My problem is that I can't get the base url for each machine.
I can get the current url using the following code:
IWebDriver driver = new FirefoxDriver();
string currentUrl = driver.Url;
But this doesn't help when I need to navigate to a different page.
Ideally I could just use the following to navigate to different pages:
driver.Navigate().GoToUrl(baseUrl+ "/Feedback");
driver.Navigate().GoToUrl(baseUrl+ "/Home");
A possible workaround I was using is:
string baseUrl = currentUrl.Remove(22); //remove everything from the current url but the base url
driver.Navigate().GoToUrl(baseUrl+ "/Feedback");
Is there a better way I could do this??
The best way around this would be to create a Uri instance of the URL.
This is because the Uri class in .NET already has code in place to do this exactly for you, so you should just use that. I'd go for something like (untested code):
string url = driver.Url; // get the current URL (full)
Uri currentUri = new Uri(url); // create a Uri instance of it
string baseUrl = currentUri.Authority; // just get the "base" bit of the URL
driver.Navigate().GoToUrl(baseUrl + "/Feedback");
Essentially, you are after the Authority property within the Uri class.
Note, there is a property that does a similar thing, called Host but this does not include port numbers, which your site does. It's something to bear in mind though.
Take the driver.Url, toss it into a new System.Uri, and use myUri.GetLeftPart(System.UriPartial.Authority).
If your base URL is http://localhost:12345/Login, this will return you http://localhost:12345.
Try this regular expression taken from this answer.
String baseUrl;
Pattern p = Pattern.compile("^(([a-zA-Z]+://)?[a-zA-Z0-9.-]+\\.[a-zA-Z]+(:\d+)?/");
Matcher m = p.matcher(str);
if (m.matches())
baseUrl = m.group(1);
I am developing an MVC Web API application that I need to access from web browsers on many different devices, for example, smart phones. During development I want to be able to debug while I access the site from my phone. To do this, I have set up Fiddler to provide a reverse proxy. Locally, the server is running on localhost:55950, but from my phone I can access the site as MyComputer:8888. This part is working.
The issue is that I am creating URIs in my REST responses. When I access the site at MyComputer:8888, I need the URIs to be something like MyComputer:8888/services/api/files, but instead I get localhost:55950/services/api/files, which fails on my phone. I am using the UrlHelper class to generate the URIs. I've looked all over, but haven't found a way to tell the system to use the referrer, not the local host. I see the desired Referrer value in the Request, so I think I could write code to patch the URI, but it seems like this would be a common issue and that there must be a way to get UrlHelper to work correctly.
I'd greatly appreciate it if anyone could point me in the right direction.
Check out this SO answer.
var httpContext = HttpContext.Current;
if (httpContext == null) {
var request = new HttpRequest("/", "http://example.com", "");
var response = new HttpResponse(new StringWriter());
httpContext = new HttpContext(request, response);
}
var httpContextBase = new HttpContextWrapper(httpContext);
var routeData = new RouteData();
var requestContext = new RequestContext(httpContextBase, routeData);
return new UrlHelper(requestContext);
I have an hyperlink that throw the exception :
"This operation is not supported for a relative URI"
Code:
Process.Start(e.Uri.AbsolutePath);
I want to enforce it to open the browser even if the uri is something like : "1aabbb3"
How can I do that ?
System.Diagnostics.Process.Start("iexplore"); should open a very specific browser to it's home page.
You can try using Uri.OriginalString
Process.Start("iexplore.exe", e.Uri.OriginalString);
Edited to reflect clarification in comment.
Solution1: check IsAbsoluteUri and use OriginalString
if (uri.IsAbsoluteUri)
Console.WriteLine("Url:{0}", uri.AbsoluteUri);
else
Console.WriteLine("Url:{0}", uri.OriginalString);
Solution2: define the url protocol
url = "http://someRelativeUrl";
uri = new Uri(url);
Console.WriteLine("Url:{0}", uri.AbsoluteUri);