How can I get the root domain URI in ASP.NET? - asp.net

Let's say I'm hosting a website at http://www.foobar.com.
Is there a way I can programmatically ascertain "http://www.foobar.com/" in my code behind (i.e. without having to hardcode it in my web config)?

string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
Uri::GetLeftPart Method:
The GetLeftPart method returns a string containing the leftmost portion of the URI string, ending with the portion specified by part.
UriPartial Enumeration:
The scheme and authority segments of the URI.

For anyone still wondering, a more complete answer is available at http://devio.wordpress.com/2009/10/19/get-absolut-url-of-asp-net-application/.
public string FullyQualifiedApplicationPath
{
get
{
//Return variable declaration
var appPath = string.Empty;
//Getting the current context of HTTP request
var context = HttpContext.Current;
//Checking the current context content
if (context != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
context.Request.Url.Scheme,
context.Request.Url.Host,
context.Request.Url.Port == 80
? string.Empty
: ":" + context.Request.Url.Port,
context.Request.ApplicationPath);
}
if (!appPath.EndsWith("/"))
appPath += "/";
return appPath;
}
}

HttpContext.Current.Request.Url can get you all the info on the URL. And can break down the url into its fragments.

If example Url is http://www.foobar.com/Page1
HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"
HttpContext.Current.Request.Url.Host; //returns "www.foobar.com"
HttpContext.Current.Request.Url.Scheme; //returns "http/https"
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"

string hostUrl = Request.Url.Scheme + "://" + Request.Url.Host; //should be "http://hostnamehere.com"

To get the entire request URL string:
HttpContext.Current.Request.Url
To get the www.foo.com portion of the request:
HttpContext.Current.Request.Url.Host
Note that you are, to some degree, at the mercy of factors outside your ASP.NET application. If IIS is configured to accept multiple or any host header for your application, then any of those domains which resolved to your application via DNS may show up as the Request Url, depending on which one the user entered.

Match match = Regex.Match(host, "([^.]+\\.[^.]{1,3}(\\.[^.]{1,3})?)$");
string domain = match.Groups[1].Success ? match.Groups[1].Value : null;
host.com => return host.com
s.host.com => return host.com
host.co.uk => return host.co.uk
www.host.co.uk => return host.co.uk
s1.www.host.co.uk => return host.co.uk

--Adding the port can help when running IIS Express
Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port

string domainName = Request.Url.Host

I know this is older but the correct way to do this now is
string Domain = HttpContext.Current.Request.Url.Authority
That will get the DNS or ip address with port for a server.

This works also:
string url = HttpContext.Request.Url.Authority;

C# Example Below:
string scheme = "http://";
string rootUrl = default(string);
if (Request.ServerVariables["HTTPS"].ToString().ToLower() == "on")
{
scheme = "https://";
}
rootUrl = scheme + Request.ServerVariables["SERVER_NAME"].ToString();

string host = Request.Url.Host;
Regex domainReg = new Regex("([^.]+\\.[^.]+)$");
HttpCookie cookie = new HttpCookie(cookieName, "true");
if (domainReg.IsMatch(host))
{
cookieDomain = domainReg.Match(host).Groups[1].Value;
}

This will return specifically what you are asking.
Dim mySiteUrl = Request.Url.Host.ToString()
I know this is an older question. But I needed the same simple answer and this returns exactly what is asked (without the http://).

Related

AES encryption via URL [duplicate]

How can I decode an encoded URL parameter using C#?
For example, take this URL:
my.aspx?val=%2Fxyz2F
string decodedUrl = Uri.UnescapeDataString(url)
or
string decodedUrl = HttpUtility.UrlDecode(url)
Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:
private static string DecodeUrlString(string url) {
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
return newUrl;
}
Server.UrlDecode(xxxxxxxx)
Have you tried HttpServerUtility.UrlDecode or HttpUtility.UrlDecode?
Try:
var myUrl = "my.aspx?val=%2Fxyz2F";
var decodeUrl = System.Uri.UnescapeDataString(myUrl);
Try this:
string decodedUrl = HttpUtility.UrlDecode("my.aspx?val=%2Fxyz2F");

Check a URL exists in ASP.NET with timeout

I have 5 sites and a domain like x.company.com.
I want use x.company.com as a load balancer to send users to x1 .. x5 sub domains.
before send users to special sub domain I want check sub domain services is alive.
Now I do these but check of sub domain maybe too late to response, so I want
check sub domain service for 2 second and if no responses go to check another sub domain.
How to do that with c# asp.net?
or anybody have better suggestions for this balancing?
My code for check URL is:
private bool HttpExists(string url)
{
// If the url does not contain Http. Add it.
if (!url.Contains("http://"))
{
url = "http://" + url;
}
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
ServicePointManager.Expect100Continue = false;
request.Proxy = WebRequest.DefaultWebProxy;
request.Proxy = null;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}

HttpUrlConnection response code always returns -1

I have created my server in amazon ec2 instance. Through my android app i am connecting to the server with HttpUrlConnection. But i get response code as -1. Does anyone has any idea ?? Here is my code.
private String getHttpResponse(final String srcUrl) {
HttpURLConnection urlConnection = null;
FileOutputStream fos = null;
try {
URL url = new URL(srcUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/json");
mETag = readETagFromPrefForCategory();
urlConnection.setRequestProperty("If-None-Match", mETag);
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xyz", "abc".toCharArray());
}
});
urlConnection.connect();
mETag = urlConnection.getHeaderField("ETag");
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
Log.v("http","not modifed");
return readLocalJson();
}
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.w(TAG, "Bad response [" + urlConnection.getResponseCode() + "] from (" + srcUrl + ")");
return null;
}}//end of try block
An answer in this post seemed to solve it for a few people:
Android Https Status code -1
Hope that helps.
The problem might be that your headers HTTP version is not properly formatted. Check this SO link where I have answered a similar question which worked for me.
Java Http~URLConnection response code -1
Why are you setting "Content-Type" on a GET request?

How do I get the site root URL?

I want to get the absolute root Url of an ASP.NET application dynamically. This needs to be the full root url to the application in the form: http(s)://hostname(:port)/
I have been using this static method:
public static string GetSiteRootUrl()
{
string protocol;
if (HttpContext.Current.Request.IsSecureConnection)
protocol = "https";
else
protocol = "http";
StringBuilder uri = new StringBuilder(protocol + "://");
string hostname = HttpContext.Current.Request.Url.Host;
uri.Append(hostname);
int port = HttpContext.Current.Request.Url.Port;
if (port != 80 && port != 443)
{
uri.Append(":");
uri.Append(port.ToString());
}
return uri.ToString();
}
BUT, what if I don't have HttpContext.Current in scope?
I have encountered this situation in a CacheItemRemovedCallback.
For WebForms, this code will return the absolute path of the application root, regardless of how nested the application may be:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/")
The first part of the above returns the scheme and domain name of the application (http://localhost) without a trailing slash. The ResolveUrl code returns a relative path to the application root (/MyApplicationRoot/). By combining them together, you get the absolute path of the web forms application.
Using MVC:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~/")
or, if you are trying to use it directly in a Razor view:
#HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)#Url.Content("~/")
You might try getting the raw URL and trimming off everything after the path forward slash. You could also incorporate ResolveUrl("~/").
public static string GetAppUrl()
{
// This code is tested to work on all environments
var oRequest = System.Web.HttpContext.Current.Request;
return oRequest.Url.GetLeftPart(System.UriPartial.Authority)
+ System.Web.VirtualPathUtility.ToAbsolute("~/");
}
public static string GetFullRootUrl()
{
HttpRequest request = HttpContext.Current.Request;
return request.Url.AbsoluteUri.Replace(request.Url.AbsolutePath, String.Empty);
}
I've solved this by adding a web.config setting in AppSettings ("SiteRootUrl"). Simple and effective, but yet another config setting to maintain.
UrlHelper url = new UrlHelper(filterContext.RequestContext);
string helpurl = url.Action("LogOn", "Account", new { area = "" },
url.RequestContext.HttpContext.Request.Url.Scheme);
Can get you the absolute url
#saluce had an excellent idea, but his code still requires an object reference and therefore can't run in some blocks of code. With the following, as long as you have a Current.Request the following will work:
With HttpContext.Current.Request
Return .Url.GetLeftPart(UriPartial.Authority) + .ApplicationPath + If(.ApplicationPath = "/", Nothing, "/")
End With
This will work no matter the protocol, port, or root folder.
This has always worked for me
string root = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, "");
Based off Uri's but stripping query strings and handling when it is a virtual directory off IIS:
private static string GetSiteRoot()
{
string siteRoot = null;
if (HttpContext.Current != null)
{
var request = HttpContext.Current.Request;
siteRoot = request.Url.AbsoluteUri
.Replace(request.Url.AbsolutePath, String.Empty) // trim the current page off
.Replace(request.Url.Query, string.Empty); // trim the query string off
if (request.Url.Segments.Length == 4)
{
// If hosted in a virtual directory, restore that segment
siteRoot += "/" + request.Url.Segments[1];
}
if (!siteRoot.EndsWith("/"))
{
siteRoot += "/";
}
}
return siteRoot;
}

ASP.NET (MVC) Get username from URL http://username#myapplication.com

Is there any way to retrieve username from this
http://username#myapplication.com
type of address in ASP.NET MVC (optionally in ASP.NET) from current request?
You're looking for the Uri class:
var uri = new Uri(someString, UriKind.Absolute);
var user = uri.UserInfo;
If that's the guaranteed string you might try something like:
string myString = "http://username#myapplication.com";
if(myString.Contains("#"))
{
return myString.Split('#')[0].Replace("http://","");
}

Resources