Find application root URL without using ~ - asp.net

I need to construct the URL of a page in a String, to send it an email (as part of an email verification system). If i use the ~ symbol to denote the app root, it is taken literally.
The app will be deployed on a server on three different sites (on different ports) and each site can be accessed via 2 different URLs (one for LAn and one for internet).
So hardcoding the URL is out of question. I want to construct the url to verify.aspx in my application
Please help

You need this:
HttpContext.Current.Request.ApplicationPath
It's equivalent to "~" in a URL.
http://msdn.microsoft.com/en-us/library/system.web.httprequest.applicationpath.aspx

Unfortunately none of the methods listed generated the full url starting from http://---.
So i had to extract these from request.url. Something like this
Uri url=HttpContext.Current.Request.Url;
StringBuilder urlString = new StringBuilder();
urlString.Append(url.Scheme);
urlString.Append("://");
urlString.Append(url.Authority);
urlString.Append("/MyDesiredPath");
Can someone spot any potential problems with this?

Try:
HttpRequest req = HttpContext.Current.Request;
string url = req.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped)
+ ((req.ApplicationPath.Length > 1) ? req.ApplicationPath : "");

You need to put the URL as part of your web application's configuration. The web application does not know how it can be reached from the outside world.
E.g. consider a scenario where there's multiple proxies and load balancers in front of your web server... how would the web server know anything but its own IP?
So, you need to configure each instance of your web application by adding the base URL e.g. as an app setting in its web.config.

You can use HttpRequest.RawURL (docs here)property and base your URL on that, but if you are behind any kind of redirection, the RawURL may not reflect the actual URL of your application.

I ended up with this. I take the request url, and use the position of Request.ApplicationRoot to discover the left part of the uri. Should work with applications hosted in a virtual directory "/example" or in the root "/".
private string GetFullUrl(string relativeUrl)
{
if (string.IsNullOrWhiteSpace(relativeUrl))
throw new ArgumentNullException("relativeUrl");
if (!relativeUrl.StartsWith("/"))
throw new ArgumentException("url should start with /", "relativeUrl");
string current = Request.Url.ToString();
string applicationPath = Request.ApplicationPath;
int applicationPathIndex = current.IndexOf(applicationPath, 10, StringComparison.InvariantCultureIgnoreCase);
// should not be possible
if (applicationPathIndex == -1) throw new InvalidOperationException("Unable to derive root path");
string basePath = current.Substring(0, applicationPathIndex);
string fullRoot = string.Concat(
basePath,
(applicationPath == "/") ? string.Empty : applicationPath,
relativeUrl);
return fullRoot;
}

This has always worked for me:
string root = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, "");

Related

Get string from current URL

I am writing an asp.net MVC Application. I have the application send a request to FreeAgent and if the request is successful a code is returned in the redirect of the URL.
For example this is a copy of a successful URL.
{
http://localhost:3425/FreeAgent/Home?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state=
}
They have added the ?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state= to my URL
I need the bit after the ?code= and before &state=
I can use this to get the URL
string code = Request.Url.AbsoluteUri;
but I need help extracting the code from this
edit:
The code will be different each time it is run
You can use the System.Uri and System.Web.HttpUtility classes
string uri = "http://localhost:3425/FreeAgent/Home?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state=";
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
Then the value of the code query parameter will be available in queryDictionary["code"]

asp.net url minus pagename and querystring

I've been looking around the web for a simple and straight forward solution for the following problem but I cant seem to find anything that suits my needs.
I have an asp.net site with many subdirectories as follows.
http://mysite.com/dir1/subdir1/
http://mysite.com/dir1/subdir2/
http://mysite.com/dir2/
http://mysite.com/dir3/subdir1/
etc...
On each of my sites pages I need to extract the URL to the page minus the pagename and querystring.
So if the page name was http://mysite.com/dir1/subdir2/mypage.aspx?param=5&param2=9
I would need the following http://mysite.com/dir1/subdir2/ I cant find any properties of the httprequest object that make this URL format readily available.
Take a look at this. It should give you everything you need, especially Url.Segments.
This works as well:
System.IO.Path.GetDirectoryName(url).Replace(#"\","/");
You're right, such thing is not ready so you need to make it yourself. One recipe is:
public string GetSubFolderURL()
{
string url = "http";
if (string.Equals(Request.ServerVariables["HTTPS"], "ON", StringComparison.CurrentCultureIgnoreCase))
url += "s";
url += "://";
url += Request.ServerVariables["SERVER_NAME"];
int port;
if (Int32.TryParse(Request.ServerVariables["SERVER_PORT"], out port) && port != 80)
url += ":" + port;
url += Request.ServerVariables["SCRIPT_NAME"];
return url.Substring(0, url.LastIndexOf("/") + 1);
}

SEO: Duplicated URLs with and without dash "/" and ASP.NET MVC

after reading this article "Slash or not to slash" (link: http://googlewebmastercentral.blogspot.com/2010/04/to-slash-or-not-to-slash.html) on Google Webmaster Central Blog (the oficial one) I decided to test my ASP.NET MVC app.
For example:
http://domain.com/products and http://domain.com/products/ (with "/" in the end), return the code 200, which means: Google understands it as two different links and likely to be a "duplicated content". They suggest to choose the way you want... with or without dash and create a 301 permanent redirect to the preferred way.
So if I choose without dash, when I try to access http://domain.com/products/ it will return a 301 to the link without dash: http://domain.com/products.
The question is, how can I do that with ASP.NET MVC?
Thanks,
Gui
If your using IIS 7 you could use the URL Rewrite Extension ScottGu has a blog post about it here.
Alternatively if you want to do it in code you could inherit from PerRequestTask. Here some sample code the removes the www from an address - this is from Shrinkr:
public class RemoveWww : PerRequestTask
{
protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext)
{
const string Prefix = "http://www.";
Check.Argument.IsNotNull(executionContext, "executionContext");
HttpContextBase httpContext = executionContext.HttpContext;
string url = httpContext.Request.Url.ToString();
bool startsWith3W = url.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase);
bool shouldContinue = true;
if (startsWith3W)
{
string newUrl = "http://" + url.Substring(Prefix.Length);
HttpResponseBase response = httpContext.Response;
response.StatusCode = (int) HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = newUrl;
response.SuppressContent = true;
response.End();
shouldContinue = false;
}
return shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break;
}
}
You would just need to check for the url ending with a / in your code.
** Note this does use a 3rd party dll - System.Web.MVC.Extensibility namespace. **
It dosnt matter really for Google, but what does matter is if both urls'
http://domain.com/products and http://domain.com/products/ show the same page, you also need to watch with windows servers that links to your site like from external pages where the user has typed http://domain.com/PRODUCTS/ will aloso be seen as a diffrent page as the web is case sensitive.
There is away round this with the use of canonical url meta tag, it tell s google what the page name is really, so will avoid duplicate pages which ant really diuplicate
http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html
you need to check the URI in the INIT event and check the URI to see if it coming in with the slash, if it is, simply do a redirect and add the 301 header to the output response.

What's the best method in ASP.NET to obtain the current domain?

I am wondering what the best way to obtain the current domain is in ASP.NET?
For instance:
http://www.domainname.com/subdir/ should yield http://www.domainname.com
http://www.sub.domainname.com/subdir/ should yield http://sub.domainname.com
As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.
Same answer as MattMitchell's but with some modification.
This checks for the default port instead.
Edit: Updated syntax and using Request.Url.Authority as suggested
$"{Request.Url.Scheme}{System.Uri.SchemeDelimiter}{Request.Url.Authority}"
As per this link a good starting point is:
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
However, if the domain is http://www.domainname.com:500 this will fail.
Something like the following is tempting to resolve this:
int defaultPort = Request.IsSecureConnection ? 443 : 80;
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
+ (Request.Url.Port != defaultPort ? ":" + Request.Url.Port : "");
However, port 80 and 443 will depend on configuration.
As such, you should use IsDefaultPort as in the Accepted Answer above from Carlos Muñoz.
Request.Url.GetLeftPart(UriPartial.Authority)
This is included scheme.
WARNING! To anyone who uses Current.Request.Url.Host. Understand that you are working based on the CURRENT REQUEST and that the current request will not ALWAYS be with your server and can sometimes be with other servers.
So if you use this in something like, Application_BeginRequest() in Global.asax, then 99.9% of the time it will be fine, but 0.1% you might get something other than your own server's host name.
A good example of this is something I discovered not long ago. My server tends to hit http://proxyjudge1.proxyfire.net/fastenv from time to time. Application_BeginRequest() gladly handles this request so if you call Request.Url.Host when it's making this request you'll get back proxyjudge1.proxyfire.net. Some of you might be thinking "no duh" but worth noting because it was a very hard bug to notice since it only happened 0.1% of the time : P
This bug has forced me to insert my domain host as a string in the config files.
Why not use
Request.Url.Authority
It returns the whole domain AND the port.
You still need to figure http or https
Simple and short way (it support schema, domain and port):
Use Request.GetFullDomain()
// Add this class to your project
public static class HttpRequestExtensions{
public static string GetFullDomain(this HttpRequestBase request)
{
var uri= request?.UrlReferrer;
if (uri== null)
return string.Empty;
return uri.Scheme + Uri.SchemeDelimiter + uri.Authority;
}
}
// Now Use it like this:
Request.GetFullDomain();
// Example output: https://example.com:5031
// Example output: http://example.com:5031
Another way:
string domain;
Uri url = HttpContext.Current.Request.Url;
domain= url.AbsoluteUri.Replace(url.PathAndQuery, string.Empty);
How about:
NameValueCollection vars = HttpContext.Current.Request.ServerVariables;
string protocol = vars["SERVER_PORT_SECURE"] == "1" ? "https://" : "http://";
string domain = vars["SERVER_NAME"];
string port = vars["SERVER_PORT"];
In Asp.Net Core 3.1 if you want to get a full domain, here is what you need to do:
Step 1: Define variable
private readonly IHttpContextAccessor _contextAccessor;
Step 2: DI into the constructor
public SomeClass(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
Step 3: Add this method in your class:
private string GenerateFullDomain()
{
string domain = _contextAccessor.HttpContext.Request.Host.Value;
string scheme = _contextAccessor.HttpContext.Request.Scheme;
string delimiter = System.Uri.SchemeDelimiter;
string fullDomainToUse = scheme + delimiter + domain;
return fullDomainToUse;
}
//Examples of usage GenerateFullDomain() method:
//https://example.com:5031
//http://example.com:5031
Using UriBuilder:
var relativePath = ""; // or whatever-path-you-want
var uriBuilder = new UriBuilder
{
Host = Request.Url.Host,
Path = relativePath,
Scheme = Request.Url.Scheme
};
if (!Request.Url.IsDefaultPort)
uriBuilder.Port = Request.Url.Port;
var fullPathToUse = uriBuilder.ToString();
How about:
String domain = "http://" + Request.Url.Host

How do I convert a file path to a URL in ASP.NET

Basically I have some code to check a specific directory to see if an image is there and if so I want to assign a URL to the image to an ImageControl.
if (System.IO.Directory.Exists(photosLocation))
{
string[] files = System.IO.Directory.GetFiles(photosLocation, "*.jpg");
if (files.Length > 0)
{
// TODO: return the url of the first file found;
}
}
this is what i use:
private string MapURL(string path)
{
string appPath = Server.MapPath("/").ToLower();
return string.Format("/{0}", path.ToLower().Replace(appPath, "").Replace(#"\", "/"));
}
As far as I know, there's no method to do what you want; at least not directly. I'd store the photosLocation as a path relative to the application; for example: "~/Images/". This way, you could use MapPath to get the physical location, and ResolveUrl to get the URL (with a bit of help from System.IO.Path):
string photosLocationPath = HttpContext.Current.Server.MapPath(photosLocation);
if (Directory.Exists(photosLocationPath))
{
string[] files = Directory.GetFiles(photosLocationPath, "*.jpg");
if (files.Length > 0)
{
string filenameRelative = photosLocation + Path.GetFilename(files[0])
return Page.ResolveUrl(filenameRelative);
}
}
The problem with all these answers is that they do not take virtual directories into account.
Consider:
Site named "tempuri.com/" rooted at c:\domains\site
virtual directory "~/files" at c:\data\files
virtual directory "~/files/vip" at c:\data\VIPcust\files
So:
Server.MapPath("~/files/vip/readme.txt")
= "c:\data\VIPcust\files\readme.txt"
But there is no way to do this:
MagicResolve("c:\data\VIPcust\files\readme.txt")
= "http://tempuri.com/files/vip/readme.txt"
because there is no way to get a complete list of virtual directories.
I've accepted Fredriks answer as it appears to solve the problem with the least amount of effort however the Request object doesn't appear to conatin the ResolveUrl method.
This can be accessed through the Page object or an Image control object:
myImage.ImageUrl = Page.ResolveUrl(photoURL);
myImage.ImageUrl = myImage.ResolveUrl(photoURL);
An alternative, if you are using a static class as I am, is to use the VirtualPathUtility:
myImage.ImageUrl = VirtualPathUtility.ToAbsolute(photoURL);
This worked for me:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath + "ImageName";
Maybe this is not the best way, but it works.
// Here is your path
String p = photosLocation + "whatever.jpg";
// Here is the page address
String pa = Page.Request.Url.AbsoluteUri;
// Take the page name
String pn = Page.Request.Url.LocalPath;
// Here is the server address
String sa = pa.Replace(pn, "");
// Take the physical location of the page
String pl = Page.Request.PhysicalPath;
// Replace the backslash with slash in your path
pl = pl.Replace("\\", "/");
p = p.Replace("\\", "/");
// Root path
String rp = pl.Replace(pn, "");
// Take out same path
String final = p.Replace(rp, "");
// So your picture's address is
String path = sa + final;
Edit: Ok, somebody marked as not helpful. Some explanation: take the physical path of the current page, split it into two parts: server and directory (like c:\inetpub\whatever.com\whatever) and page name (like /Whatever.aspx). The image's physical path should contain the server's path, so "substract" them, leaving only the image's path relative to the server's (like: \design\picture.jpg). Replace the backslashes with slashes and append it to the server's url.
So far as I know there's no single function which does this (maybe you were looking for the inverse of MapPath?). I'd love to know if such a function exists. Until then, I would just take the filename(s) returned by GetFiles, remove the path, and prepend the URL root. This can be done generically.
The simple solution seems to be to have a temporary location within the website that you can access easily with URL and then you can move files to the physical location when you need to save them.
For get the left part of the URL:
?HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)
"http://localhost:1714"
For get the application (web) name:
?HttpRuntime.AppDomainAppVirtualPath
"/"
With this, you are available to add your relative path after that obtaining the complete URL.
I think this should work. It might be off on the slashes. Not sure if they are needed or not.
string url = Request.ApplicationPath + "/" + photosLocation + "/" + files[0];

Resources