Check if it is root domain in string - c#

I'm new to C#,
lets say I have a string
string testurl = "http://www.mytestsite.com/hello";
if (test url == root domain) {
// do something
}
I want to check if that string "testurl" is the root domain i.e http://www.mytestsite.com or http://mytestsite.com etc.
Thanks.

Use the Uri class:
var testUrl = new Uri("http://www.mytestsite.com/hello");
if (testUrl.AbsolutePath== "/")
{
Console.WriteLine("At root");
}
else
{
Console.WriteLine("Not at root");
}
Which nicely deals with any normalization issues that may be required (e.g. treating http://www.mytestsite.com and http://www.mytestsite.com/ the same)

You may try like this:
string testurl = "http://www.mytestsite.com/hello"
if ( GetDomain.GetDomainFromUrl(testurl) == rootdomain) {
// do something
}

You can also try using URI.HostName property
The following example writes the host name (www.contoso.com) of the server to the console.
Uri baseUri = new Uri("http://www.contoso.com:8080/");
Uri myUri = new Uri(baseUri, "shownew.htm?date=today");
Console.WriteLine(myUri.Host);
If the hostname returned is equal to "http://mytestsite.com" you are done.

string testurl = "http://www.mytestsite.com/hello";
string prefix = testurl.Split(new String[] { "//" })[0] + "//";
string url = testurl.Replace(prefix, "");
string root = prefix + url.Split("/")[0];
if (testurl == root) {
// do something
}

Related

Find the applicant's current URl

I'm request for get url :
public Uri GetAbsoluteUri()
{
var request = _httpContextAccessor.HttpContext.Request;
UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = request.Scheme;
uriBuilder.Host = request.Host.Host;
uriBuilder.Path = request.Path.ToString();
uriBuilder.Query = request.QueryString.ToString();
return uriBuilder.Uri;
}
public string RootPath => Path.Combine(WebRootPath, RootFolderName);
public string GetProductPicturePath()
{
return Path.Combine(GetAbsoluteUri().ToString(), RootFolderName, ProductPictureFolder);
}
public string GetProductMainPicturePath()
{
string path = Path.Combine(GetAbsoluteUri().ToString(), RootFolderName, ProductPictureFolder, ProductMainPictureFolder);
return path;
}
public string GetNewPath()
{
string productMainPicturePath = GetProductMainPicturePath();
return Path.Combine(productMainPicturePath);
}
finally i using the GetNewPath().
, but this will give me the address :
https://localhost/api/Product/GetProductList/Upload/ProductPictureFolder/ProductMainPicture/77777.png
but i have 2 problem with this url :
1 - it not contain port in url https://localhost/api but i need return like this : http://localhost:4200/api
2 - This includes the name of the controller and the ActionName, but I need to like this : https://localhost/Upload/ProductPictureFolder/ProductMainPicture/77777.png
but it return for me this : https://localhost/api/Product/GetProductList/Upload/ProductPictureFolder/ProductMainPicture/77777.png
i not need this /api/Product/GetProductList .
Product : Controller Name
GetProductList : ActionName
How Can I Solve This Problem ???
1 - it not contain port in url https://localhost/api but i need return like this
To get port you can use this snippet :
if (request.Host.Port.HasValue)
uriBuilder.Port = request.Host.Port.Value;
2 - This includes the name of the controller and the ActionName, but I
need to like this :
https://localhost/Upload/ProductPictureFolder/ProductMainPicture/77777.png
I suggest you that set UriBuilder Path based on your needs, not from the request. Something like this:
// Make your Upload file path here
var relativePath = Path.Combine(folderName, filename);
var request = _httpContextAccessor.HttpContext.Request;
var uriBuilder = new UriBuilder
{
Host = request.Host.Host,
Scheme = request.Scheme,
Path = relativePath
};
if (request.Host.Port.HasValue)
uriBuilder.Port = request.Host.Port.Value;
var imageUrl = uriBuilder.ToString();

How to remove backslash from url when returning from c# code?

public Uri GetCrmUrl(string phone,string organisationid,string server)
{
string _URL = string.Empty;
string clienturl = #"https://petsolutions.crm8.dynamics.com/nga/engagementhub.aspx?org="+organisationid+"&server="+server;
Uri x = new Uri(clienturl,UriKind.Absolute);
return x;
}
I am trying to returning this url directly on html .
But the value returning is like:
https:\/\/petsolutions.crm8.dynamics.com\/nga\/engagementhub.aspx?org=dkejverv&server=dfvfevf
while the expected output is:
https://petsolutions.crm8.dynamics.com/nga/engagementhub.aspx?org=dkejverv&server=dfvfevf
How can i remove those slashes from my URL ?
In C# code, code is returning correct values but at the time of HTML Rendering there are some backslashes there. Check Image Here
Maybe you should try the String.Replace() method:
string test = clienturl.Replace(#"\", string.empty);
Uri x = new Uri(test ,UriKind.Absolute);
return x;
I don't know where you are looking for your string but this example works just the way you want:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Uri test = GetCrmUrl("00000", "orgid", "server");
Console.WriteLine(test);
Console.ReadKey();
}
public static Uri GetCrmUrl(string phone, string organisationid, string server)
{
string clienturl = #"https://petsolutions.crm8.dynamics.com/nga/engagementhub.aspx?org=" + organisationid + "&server=" + server;
Uri x = new Uri(clienturl, UriKind.Absolute);
return x;
}
}
}
Returns:
https://petsolutions.crm8.dynamics.com/nga/engagementhub.aspx?org=orgid&server=server
No need to remove slashes at all.
try this :
return new Uri(HttpUtility.HtmlDecode(clienturl).ToString());

Comparing different urls for save domain

Introduction:
I have a start url suppose www.example.com now i run scraper on this url to collect all the internal links belonging to same site and external links.
Problem:
I am using the code below to compare a found url with the main url www.example.com to see if they both have same domain so i take the url as internal url.
Uri baseUri = new Uri(url); //main URL
Uri myUri = new Uri(baseUri, strRef); //strRef is new found link
//domain = baseUri.Host;
domain = baseUri.Host.Replace("www.", string.Empty).Replace("http://", string.Empty).Replace("https://", string.Empty).Trim();
string domain2=myUri.Host.Replace("www.", string.Empty).Replace("http://", string.Empty).Replace("https://", string.Empty).Trim();
strRef = myUri.ToString();
if (domain2==(domain) )
{ //DO STUFF }
Is the above the correct logic ? Because if supposing i get a new url http://news.example.com the domain name found becomes : news.example.com which does not match the domain name of the main url . Is this correct?Should it match or not . And What is a better way if mine is not good enough.
here is a solution to find main domain from subdomain
string url = "http://www.xxx.co.uk";
string strRef = "http://www.news.xxx.co.uk";
Uri baseUri = new Uri(url); //main URL
Uri myUri = new Uri(baseUri, strRef); //strRef is new found link
var domain = baseUri.Host;
domain = baseUri.Host.Replace("www.", string.Empty).Replace("http://", string.Empty).Replace("https://", string.Empty).Trim();
//hrere is solution
string domain2 = GetDomainName(strRef);
strRef = myUri.ToString();
if (domain2 == (domain))
{ //DO STUFF
}
private static string GetDomainName(string url)
{
string domain = new Uri(url).DnsSafeHost.ToLower();
var tokens = domain.Split('.');
if (tokens.Length > 2)
{
//Add only second level exceptions to the < 3 rule here
string[] exceptions = { "info", "firm", "name", "com", "biz", "gen", "ltd", "web", "net", "pro", "org" };
var validTokens = 2 + ((tokens[tokens.Length - 2].Length < 3 || exceptions.Contains(tokens[tokens.Length - 2])) ? 1 : 0);
domain = string.Join(".", tokens, tokens.Length - validTokens, validTokens);
}
return domain;
}

Parse variable URI (RegEx, Uri, String-Functions?) c#

I'm writing a RTSP client module and for this, I need to parse an very variable URI. But I'm completely stuck about which method I should use (most-failsafe) and how to accomplish this.
An example URI could look like this:
rtsp://192.168.1.100:554/videocam/media/1/video/1
\_/ \_______________/\_______/\______________/
| | | |
scheme authority [sub] [mediacontrol]
But also other possibilities:
192.168.1.100/videocam/media/1/video/1
192.168.1.100:6000/media/1/video/1
192.168.1.100:6000/videocam
I need the following information:
IP | how can I recognise this pattern [num].[num].[num].[num]?
Port | easy if the string contains rtsp://, but what about just a number? 1-65555
Sub | Optional subpath, can completely vary!
MediaLevel | Optional MediaLevel (indicator for stream/track),
not to be confused with the path. MediaLevel can be also just like this: track1 or m1s3 or media1/video1.. see?
I can't go for the slash, also the path also can contain multiple slashes
Maybe there's a library for such tasks?
Thank you.
var uri = new Uri("rtsp://192.168.1.100:554/videocam/media/1/video/1");
var host = uri.Host;
var port = uri.Port;
var sub = uri.Segments[1];
var mlevel = uri.Segments.Skip(2).ToArray();
Here is a quick example of how to use the UriBuilder class. It is a bit verbose because it is an example and is not ready for production. If more subs are to be identified then they can be added to the Sub List as shown in the example.
class Program
{
private static string _scheme = string.Empty;
private static string _host = string.Empty;
private static string _sub = string.Empty;
static void Main(string[] args)
{
ParseUri("rtsp://192.168.1.100:554/videocam/media/1/video/1");
ParseUri("192.168.1.100/videocam/media/1/video/1");
ParseUri("192.168.1.100:6000/media/1/video/1");
ParseUri("192.168.1.100:6000/videocam");
// example of adding a new sub
Sub.Add("sample");
ParseUri("192.168.1.100:6000/sample/");
Console.ReadLine();
}
private static void ParseUri(string URI)
{
UriBuilder uri = new UriBuilder(URI);
_scheme = uri.Scheme;
_host = uri.Host;
_sub = string.Empty;
StringBuilder sb = new StringBuilder();
foreach (string s in uri.Uri.Segments)
{
if (Sub.Contains(s.Replace("/","")))
{_sub = s;}
else
{ sb.Append(s); }
}
Console.Out.WriteLine("+++++++++++++");
Console.Out.WriteLine("URI: {0}",URI);
Console.Out.WriteLine("Scheme: {0}", _scheme);
Console.Out.WriteLine("sub: {0}",_sub);
Console.Out.WriteLine("mediaControl: {0}", sb.ToString());
}
private static List<string> Sub
{
get
{
List<string> sub = new List<string>();
sub.Add("videocam");
return sub;
}
}
}
trace("Url : {0}", turl.Text);
var uri = new Uri(turl.Text);
string host = uri.Host;
int port = uri.Port;
string userInfo = uri.UserInfo;
string subStream = "";
string userName = "";
string password = "";
if (uri.Segments?.Any() == true)
{
subStream = string.Join("", uri.Segments);
}
if (!string.IsNullOrEmpty(userInfo))
{
if (userInfo.Contains(":"))
{
string[] data = userInfo.Split(':');
userName = data[0];
password = data[1];
}
else
{
userName = userInfo;
}
}
trace("host : {0}", host);
trace("port : {0}", port);
trace("userName : {0}", userName);
trace("password : {0}", password);
trace("subStream: {0}", subStream);

Replace host in Uri

What is the nicest way of replacing the host-part of an Uri using .NET?
I.e.:
string ReplaceHost(string original, string newHostName);
//...
string s = ReplaceHost("http://oldhostname/index.html", "newhostname");
Assert.AreEqual("http://newhostname/index.html", s);
//...
string s = ReplaceHost("http://user:pass#oldhostname/index.html", "newhostname");
Assert.AreEqual("http://user:pass#newhostname/index.html", s);
//...
string s = ReplaceHost("ftp://user:pass#oldhostname", "newhostname");
Assert.AreEqual("ftp://user:pass#newhostname", s);
//etc.
System.Uri does not seem to help much.
System.UriBuilder is what you are after...
string ReplaceHost(string original, string newHostName) {
var builder = new UriBuilder(original);
builder.Host = newHostName;
return builder.Uri.ToString();
}
As #Ishmael says, you can use System.UriBuilder. Here's an example:
// the URI for which you want to change the host name
var oldUri = Request.Url;
// create a new UriBuilder, which copies all fragments of the source URI
var newUriBuilder = new UriBuilder(oldUri);
// set the new host (you can set other properties too)
newUriBuilder.Host = "newhost.com";
// get a Uri instance from the UriBuilder
var newUri = newUriBuilder.Uri;

Categories