I have my local host and a live site. I have a url and if its in localhost the url should go localhost/site/thank_you.aspx and if its live http://mylivesite.com/thank_you.aspx
I have tried this in my code behind...
MyHiddenField.Value = Request.URL + "/thank_you.aspx";
but it returned the page I was on /thank_you.aspx
What am I doing wrong?
Try this, I even added scheme in too, just in case you go https :)
EDIT: Also added port (Thanks Alex) in order to be super duper super future-proof :)
MyHiddenField.Value = string.Format(
"{0}://{1}{2}/thank_you.aspx",
Request.Url.Scheme,
Request.Url.Host,
Request.Url.IsDefaultPort ? string.Empty : ":" + Request.Url.Port);
EDIT: Another good suggestion by #MikeSmithDev, put it in a function
public string GetUrlForPage(string page)
{
return MyHiddenField.Value = string.Format(
"{0}://{1}{2}/{3}",
Request.Url.Scheme,
Request.Url.Host,
Request.Url.IsDefaultPort ? string.Empty : ":" + Request.Url.Port,
page);
}
Then you can do:
MyHiddenField.Value = GetUrlForPage("thank_you.aspx");
There is a built-in class UriBuilder
var url = Request.Url;
var newurl = new UriBuilder(url.Scheme, url.Host, url.Port, "thank_you.aspx")
.ToString();
Adding to the answers above. Allow function to handle relative paths. For example: ~/ or ~/test/default.aspx
public string GetUrlForPage(string relativeUrl)
{
return string.Format(
"{0}://{1}{2}{3}",
Request.Url.Scheme,
Request.Url.Host,
Request.Url.IsDefaultPort ? string.Empty : ":" + Request.Url.Port,
Page.ResolveUrl(relativeUrl));
}
Related
I am wanting to redirect a page to a secure connection for an ASPX file.
Clients are asked to copy and paste a URL that looks like this foo.com.au into the browser.
I have this code below working on the code behind file but am wondering when it is deployed to production if this will update the URL to have www after the https://www as the URL provided to clients does not have www in it?
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (!Request.IsLocal && !Request.IsSecureConnection)
{
string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
Response.Redirect(redirectUrl);
}
}
Rather than using Request.Url, use Request.Url.AbsoluteUri. In addition, you should not assume that the URL will be entered in lowercase. I would revise the code to be:
if (!Request.IsLocal && !Request.IsSecureConnection)
{
if (Request.Url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase))
{
string sNonSchemeUrl = Request.Url.AbsoluteUri.Substring(Uri.UriSchemeHttp.Length);
// Ensure www. is prepended if it is missing
if (!sNonSchemeUrl.StartsWith("www", StringComparison.InvariantCultureIgnoreCase)) {
sNonSchemeUrl = "www." + sNonSchemeUrl;
}
string redirectUrl = Uri.UriSchemeHttps + sNonSchemeUrl;
Response.Redirect(redirectUrl);
}
}
If you do this, all it will change is the schema. So, if the absoluteUri is
http://foo.com.au
it will be changed to
https://foo.com.au
One last note: when we have done this, we have never tried it in OnPreInit, we always perform this logic in Page_Load. I am not sure what, if any, ramifications there will be for redirecting at that portion of the page lifecycle, but if you run into issues, you could move it into Page_Load.
This was my final implementation to account for a request comes through for https://foo and not https://www.foo
if (!Request.IsLocal &&
!Request.Url.AbsoluteUri.StartsWith("https://www.", StringComparison.OrdinalIgnoreCase))
{
string translatedUrl;
string nonSchemeUrl = Request.Url.AbsoluteUri;
string stringToReplace = (Request.Url.Scheme == Uri.UriSchemeHttp ? Uri.UriSchemeHttp + "://" : Uri.UriSchemeHttps + "://");
nonSchemeUrl = nonSchemeUrl.Replace(stringToReplace, string.Empty);
if (!nonSchemeUrl.StartsWith("www", StringComparison.InvariantCultureIgnoreCase))nonSchemeUrl = "www." + nonSchemeUrl;
translatedUrl = Uri.UriSchemeHttps + "://" + nonSchemeUrl;
Response.Redirect(nonSchemeUrl);
}
I can get my browser url using : string url = HttpContext.Current.Request.Url.AbsoluteUri;
But say if I have a url as below :
http://www.test.com/MyDirectory/AnotherDir/testpage.aspx
How would I get the "MyDirectory" part of it, is there a utility in .NET to get this or do I need string manipulation ?
If I do string manipulation and say anything after first instance of "/" then wouldnt it return the slash after http:? It would work if my url was www.test.com/MyDirectory/AnotherDir/testpage.aspx
Can someone please help
Instantiate a Uri instance from your url:
Uri myUri = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
You can then get the path segments into a string array using:
string[] segments = myUri.Segments
Your first "MyDirectory" folder will be at:
string myFolderName = segments[0];
You can get this by PathAndQuery property of Url
var path = HttpContext.Current.Request.Url.PathAndQuery;
it will return /MyDirectory/AnotherDir/testpage.aspx
Uri uriAddr = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
var firstSegment= uriAddress.Segments.Where(seg => seg != "/").First();
In an ASP.NET Application running from within an IIS. What is the correct way to find the URL of my application. I mean the IIS configuration, ignoring proxies, redirection and URL rewriting.
Thank you
I would really prefer it not to be dependent on a request...
try this :
Request.ServerVariables[ "HTTP_URL" ]
Here's how it should work:
string app = HttpContext.Current.Request.PhysicalApplicationPath;
what do you mean "URL of my application"?
to get the physical app path: string path= HttpContext.Current.Request.ApplicationPath;
or try this if this is what you want: string path = System.AppDomain.CurrentDomain.BaseDirectory;
string app = HttpContext.Current.Request.ApplicationPath;
That should do the trick.
Try this other option:
Uri uri = HttpContext.Current.Request.Url;
string strCompleteUrl = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port + uri.AbsolutePath;
I have a base URL :
http://my.server.com/folder/directory/sample
And a relative one :
../../other/path
How to get the absolute URL from this ? It's pretty straighforward using string manipulation, but I would like to do this in a secure way, using the Uri class or something similar.
It's for a standard a C# app, not an ASP.NET one.
var baseUri = new Uri("http://my.server.com/folder/directory/sample");
var absoluteUri = new Uri(baseUri,"../../other/path");
OR
Uri uri;
if ( Uri.TryCreate("http://base/","../relative", out uri) ) doSomething(uri);
Some might be looking for Javascript solution that would allow conversion of urls 'on the fly' when debugging
var absoluteUrl = function(href) {
var link = document.createElement("a");
link.href = href;
return link.href;
}
use like:
absoluteUrl("http://google.com")
http://google.com/
or
absoluteUrl("../../absolute")
http://stackoverflow.com/absolute
I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way?
Here is a list I normally refer to for this type of information:
Request.ApplicationPath : /virtual_dir
Request.CurrentExecutionFilePath : /virtual_dir/webapp/page.aspx
Request.FilePath : /virtual_dir/webapp/page.aspx
Request.Path : /virtual_dir/webapp/page.aspx
Request.PhysicalApplicationPath : d:\Inetpub\wwwroot\virtual_dir\
Request.QueryString : /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.AbsolutePath : /virtual_dir/webapp/page.aspx
Request.Url.AbsoluteUri : http://localhost:2000/virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Host : localhost
Request.Url.Authority : localhost:80
Request.Url.LocalPath : /virtual_dir/webapp/page.aspx
Request.Url.PathAndQuery : /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Port : 80
Request.Url.Query : ?q=qvalue
Request.Url.Scheme : http
Request.Url.Segments : /
virtual_dir/
webapp/
page.aspx
Hopefully you will find this useful!
I usually use Request.Url.ToString() to get the full url (including querystring), no concatenation required.
Request.Url.AbsoluteUri
This property does everything you need, all in one succinct call.
For ASP.NET Core you'll need to spell it out:
var request = Context.Request;
#($"{ request.Scheme }://{ request.Host }{ request.Path }{ request.QueryString }")
Or you can add a using statement to your view:
#using Microsoft.AspNetCore.Http.Extensions
then
#Context.Request.GetDisplayUrl()
The _ViewImports.cshtml might be a better place for that #using
if you need the full URL as everything from the http to the querystring you will need to concatenate the following variables
Request.ServerVariables("HTTPS") // to check if it's HTTP or HTTPS
Request.ServerVariables("SERVER_NAME")
Request.ServerVariables("SCRIPT_NAME")
Request.ServerVariables("QUERY_STRING")
Request.RawUrl
Better to use Request.Url.OriginalString than Request.Url.ToString() (according to MSDN)
Thanks guys, I used a combination of both your answers #Christian and #Jonathan for my specific need.
"http://" + Request.ServerVariables["SERVER_NAME"] + Request.RawUrl.ToString()
I don't need to worry about secure http, needed the servername variable and the RawUrl handles the path from the domain name and includes the querystring if present.
If you need the port number also, you can use
Request.Url.Authority
Example:
string url = Request.Url.Authority + HttpContext.Current.Request.RawUrl.ToString();
if (Request.ServerVariables["HTTPS"] == "on")
{
url = "https://" + url;
}
else
{
url = "http://" + url;
}
Try the following -
var FullUrl = Request.Url.AbsolutePath.ToString();
var ID = FullUrl.Split('/').Last();