This question already has answers here:
Get URL of ASP.Net Page in code-behind [duplicate]
(10 answers)
Closed 9 years ago.
Can anyone help out me in getting the URL of the current working page of ASP.NET in C#?
Try this :
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx
string host = HttpContext.Current.Request.Url.Host;
// localhost
You may at times need to get different values from URL.
Below example shows different ways of extracting different parts of URL
EXAMPLE: (Sample URL)
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
CODE
Response.Write("<br/>Host " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/>Authority: " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/>Port: " + HttpContext.Current.Request.Url.Port);
Response.Write("<br/>AbsolutePath: " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/>ApplicationPath: " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/>AbsoluteUri: " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/>PathAndQuery: " + HttpContext.Current.Request.Url.PathAndQuery);
OUTPUT
Host: localhost
Authority: localhost:60527
Port: 60527
AbsolutePath: /WebSite1test/Default2.aspx
ApplicationPath: /WebSite1test
AbsoluteUri: http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString1=2
PathAndQuery: /WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
You can copy paste above sample code & run it in asp.net web form application with different URL.
I also recommend reading ASP.Net Routing in case you may use ASP Routing then you don't need to use traditional URL with query string.
http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx
Just sharing as this was my solution thanks to Canavar's post.
If you have something like this:
"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"
or like this:
"https://www.something.com/index.html?a=123&b=4567"
and you only want the part that a user would type in then this will work:
String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
which would result in these:
"http://localhost:1234/"
"https://www.something.com/"
if you just want the part between http:// and the first slash
string url = Request.Url.Host;
would return stackoverflow.com if called from this page
Here's the complete breakdown
the request.rawurl will gives the content of current page
it gives the exact path that you required
use HttpContext.Current.Request.RawUrl
If you want to get
localhost:2806
from
http://localhost:2806/Pages/
then use:
HttpContext.Current.Request.Url.Authority
a tip for people who needs the path/url in global.asax file;
If you need to run this in global.asax > Application_Start and you app pool mode is integrated then you will receive the error below:
Request is not available in this context exception in
Application_Start.
In that case you need to use this:
System.Web.HttpRuntime.AppDomainAppVirtualPath
Hope will help others..
A search landed me at this page, but it wasn't quite what I was looking for. Posting here in case someone else looking for what I was lands at this page too.
There is two ways to do it if you only have a string value.
.NET way:
Same as #Canavar, but you can instantiate a new Uri Object
String URL = "http://localhost:1302/TESTERS/Default6.aspx";
System.Uri uri = new System.Uri(URL);
which means you can use the same methods, e.g.
string url = uri.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string host = uri.host
// localhost
Regex way:
Getting parts of a URL (Regex)
I guess its enough to return absolute path..
Path.GetFileName( Request.Url.AbsolutePath )
using System.IO;
Related
I am given a code and on one of its pages which shows a "search result" after showing different items, it allows user to click on one of records and it is expected to bring up a page so that specific selected record can be modified.
However, when it is trying to bring up the page I get (by IE) "This page cannot be displayed".
It is obvious the URL is wrong because first I see something http://www.Something.org/Search.aspx then it turns into http://localhost:61123/ProductPage.aspx
I did search in the code and found the following line which I think it is the cause. Now, question I have to ask:
What should I do to avoid using a static URL and make it dynamic so it always would be pointing to the right domain?
string url = string.Format("http://localhost:61123/ProductPage.aspx?BC={0}&From={1}", barCode, "Search");
Response.Redirect(url);
Thanks.
Use HttpContext.Current.Request.Url in your controller to see the URL. Url contains many things including Host which is what you're looking for.
By the way, if you're using the latest .Net 4.6+ you can create the string like so:
string url = $"{HttpContext.Current.Request.Url.Host}/ProductPage.aspx?BC={barCode}&From={"Search"}";
Or you can use string.Format
string host = HttpContext.Current.Request.Url.Host;
string url = string.Format("{0}/ProductPage.aspx?BC={1}&From={2}"), host, barCode, "Search";
You can store the Host segment in your AppSettings section of your Web.Config file (per config / environment like so)
Debug / Development Web.Config
Production / Release Web.Config (with config override to replace the localhost value with something.org host)
and then use it in your code like so.
// Creates a URI using the HostUrlSegment set in the current web.config
Uri hostUri = new Uri(ConfigurationManager.AppSettings.Get("HostUrlSegment"));
// does something like Path.Combine(..) to construct a proper Url with the hostName
// and the other url segments. The $ is a new C# construct to do string interpolation
// (makes for readable code)
Uri fullUri = new Uri(hostUri, $"ProductPage.aspx?BC={barCode}&From=Search");
// fullUrl.AbosoluteUri will contain the proper Url
Response.Redirect(fullUri.AbsoluteUri);
The Uri class has a lot of useful properties and methods to give you Relative Url, AbsoluteUrl, your Url Fragments, Host name etc etc.
This should do it.
string url = string.Format("ProductPage.aspx?BC={0}&From={1}", barCode, "Search");
Response.Redirect(url);
If you are using .Net 4.6+ you can also use this string interpolation version
string url = $"ProductPage.aspx?BC={barcode}&From=Search";
Response.Redirect(url);
You should just be able to omit the hostname to stay on the current domain.
If I use this:
Request.Url.AbsoluteUri
I get full url like:
http://localhost/mysite/Default.aspx?TabID=269&OTHER-parameters
But I don't want this thing with TabID I need friendly url so if I use:
DotNetNuke.Entities.Tabs.TabController.CurrentPage.FullUrl;
I get
http://localhost/mysite/something/en-us/generatethings.aspx
But with this I don't get parameters :(
How to get full friendly complete url from dnn with all parameters?
Unfortunately, there isn't an easy way to get the current URL within DNN, because the URL gets rewritten before it gets to your module.
What we'll typically do is regenerate the URL, using Globals.NavigateURL. You can use DotNetNuke.Common.Utilities.UrlUtils.GetQSParamsForNavigateURL to get all of the query string parameters from the current URL.
So, you'd end up with something like this:
var currentUrl = Globals.NavigateURL(
this.TabId,
this.Request.QueryString["ctl"],
UrlUtils.GetQSParamsForNavigateURL());
I think this will get you what you want
string url = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl;
`string url = TabController.CurrentPage.FullUrl;`
this should give you the user friendly url
I am trying to get a typical asp.net url starting with the tilde sign ('~') to parse into a full exact url starting with "http:"
I have this string "~/PageB.aspx"
And i want to make it become "http://myServer.com/PageB.aspx"
I know there is several methods to parse urls and get different paths of server and application and such. I have tried several but not gotten the result i want.
Try out
System.Web.VirtualPathUtility.ToAbsolute("yourRelativePath");
There are various ways that are available in ASP.NET that we can use to resolve relative paths to a resource on the server-side and making it available on the client-side. I know of 4 ways -
1) Request.ApplicationPath
2) System.Web.VirtualPathUtility
3) Page.ResolveUrl
4) Page.ResolveClientUrl
Good article : Different approaches for resolving URLs in ASP.NET
If you're in a page handler you could always use the ResolveUrl method to convert the relative path to a server specific path. But if you want the "http://www.yourserver.se" part aswell, you'll have to prepend the Request.Url.Scheme and Request.Url.Authority to it.
string.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
This method looks the nicest to me. No string manipulation, it can tolerate both relative or absolute URLs as input, and it uses the exact same scheme, authority, port, and root path as whatever the current request is using:
private Uri GetAbsoluteUri(string redirectUrl)
{
var redirectUri = new Uri(redirectUrl, UriKind.RelativeOrAbsolute);
if (!redirectUri.IsAbsoluteUri)
{
redirectUri = new Uri(new Uri(Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath), redirectUri);
}
return redirectUri;
}
the url on my local project is :-
http://localhost/mysite/KB/Type-1/General-Article
and on server it is:-
http://www.mysite.com/KB/Type-1/General-Article
from both the urls, I want to fetch the URL part until Type-1 without slash
ie from localhost website address, I want:-
http://localhost/mysite/KB/Type-1
and from server, I want :-
http://www.mysite.com/KB/Type-1
How can I do this? Please help ..thanks
Please note that Type-1 is not a fixed, it wcan change. It can be anything like "Type-2", "User-Articles", etc.
Thanks for the answers but will this still work if there is a slash at the end of the URL too?
like this:-
http://www.mysite.com/KB/Type-1/General-Article/
Please note that the text "KB" in the URL is FIXED.
try this code,
url.Substring(0, url.LastIndexOf("/")-1);
edit: if you have ending slash, you can use following code
url=url.Remove(test1.Length - 1);
url.Substring(0, url.LastIndexOf("/")-1);
since you don't provide enough information only some general idea:
EDIT 2 - as per comments:
string MySubURL = MyURL.SubString ( 0, MyURL.TrimEnd(null).TrimEnd(new char[]{'/'}).LastIndexOf ("/") );
This will do what you want whether there is a '/' at the end or not in a single line. It is a bit longer, but it works for all of your outlined requirements.
string url = "http://www.mysite.com/KB/Type-1/General-Article";
string seg = url.EndsWith("/") ? url.Substring(0, url.TrimEnd('/').LastIndexOf('/')) : url.Substring(0, url.LastIndexOf('/'));
I am following the code over here https://web.archive.org/web/20211020203216/https://www.4guysfromrolla.com/articles/072810-1.aspx
to redirect http://somesite.com to http://www.somesite.com
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Url.Authority.StartsWith("www"))
return;
var url = string.Format("{0}://www.{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Request.Url.PathAndQuery);
Response.RedirectPermanent(url, true);
}
How can I use this code to handle situations where http://abc.somesite.com should redirect to www.somesite.com
I'd suggest the best way to handle this would be in the dns record, if you have control of it.
If you don't know what the values will be ahead of time, you can use substring with indexof for the Url path to parse out the value you want and replace it.
If you do know what it is ahead of time, you can always just do Request.Url.PathAndQuery.Replace("abc", "www");
You can also do a dns check as #aceinthehole suggested after you have parsed what you need to make sure you haven't made any mistakes.
assuming you have a string like http://abc.site.com and you want to turn abc into www then you could do something like.
string pieceToReplace = Request.Url.PathAndQuery.substring(0, Request.Url.PathAndQuery.IndexOf(".") + 1);
//here I use the scheme and entire url to make sure we don't accidentally replace an "abc" that belongs later in the url like in a word "GHEabc.com" or something.
string newUrl = Request.Url.ToString().Replace(Request.Url.Scheme + "://" + pieceToReplace, Request.Url.Scheme + "://www");
Response.Redirect(newUrl);
p.s. I don't remember if the Request.Url.Scheme already has the "://" in it or not so you will need to edit accordingly.
I don't think you can do it without access to the DNS. It sounds like you need a wildcard DNS entry:
http://en.wikipedia.org/wiki/Wildcard_DNS_record
Along with IIS configured without host headers (IP only). Then you can use code similar to the above to do what you want.
if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
Response.Redirect('www.somesite.com');
Perhaps tighten it up some to prevent wwww.somesite.com from getting through. Anything that starts with www including wwwmonkeys.somesite.com would get through the above check. It is just an example.
asp.net mvc: How to redirect a non www to www and vice versa