I have been using ResolveUrl for adding CSS and Javascript in ASP.NET files.
But I usually see an option of ResolveClientUrl. What is the difference between both?
When should I use ResolveClientUrl?
ResolveUrl creates the URL relative to the root.
ResolveClientUrl creates the URL relative to the current page.
You can also use whichever one you want, however ResolveUrl is more commonly used.
Here's a simple example:
//Returns: ../HomePage.aspx
String ClientURL = ResolveClientUrl("~/HomePage.aspx");
//Returns: /HomePage.aspx
String RegURL = ResolveUrl("~/HomePage.aspx");
//Returns: C:\inetpub\wwwroot\MyProject\HomePage.aspx
String ServerMappedPath = Server.MapPath("~/HomePage.aspx");
//Returns: ~/HomePage.aspx
String appRelVirtPath = AppRelativeVirtualPath;
//Returns: http://localhost:4913/
String baseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
//Returns: "http://localhost:4913/HomePage.aspx"
String absUri = Request.Url.AbsoluteUri;
According to the MSDN documentation:
ResolveClientUrl
A fully qualified URL to the specified
resource suitable for use on the
browser.
Use the ResolveClientUrl method to
return a URL string suitable for use
by the client to access resources on
the Web server, such as image files,
links to additional pages, and so on.
ResolveUrl
The converted URL.
If the relativeUrl parameter contains an absolute URL, the URL is returned unchanged. If the relativeUrl parameter contains a relative URL, that URL is changed to a relative URL that is correct for the current request path, so that the browser can resolve the URL.
For example, consider the following
scenario:
A client has requested an ASP.NET page
that contains a user control that has
an image associated with it.
The ASP.NET page is located at
/Store/page1.aspx.
The user control is located at
/Store/UserControls/UC1.ascx.
The image file is located at
/UserControls/Images/Image1.jpg.
If the user control passes the
relative path to the image (that is,
/Store/UserControls/Images/Image1.jpg)
to the ResolveUrl method, the method
will return the value
/Images/Image1.jpg.
I think this explains it quite well.
In short:
Page.ResolveUrl(~): creates the URL from the root of app.
and
Page.ResolveClientUrl(~): creates the URL relative to the current page.(e.g: ../../..)
but in my tests in asp.net, Page.ResolveUrl is better because of stable output & is not relative.
Using Page.ResolveUrl is better if you are trying to get a Javascript friendly Url.
Like if you are opening an iframe from the parent page, you would need a full url that would be passed to the iframe src property.
Related
I want to read following URL and it should save the content available in the page to Text file.
I use below code to read page source:
string address = "view-source:http://stackoverflow.com/"; //any web site url
using (WebClient wc = new WebClient())
{
var Text= wc.DownloadString(address);
}
But it is throwing exception "The URI prefix is not recognized."
Any Help Would be Appreciate.
Thanks! in advance.
You're using a feature of Chrome by prepending "view-source:" to that url. The WebClient class probably doesn't know anything about that feature. It's complaining about the "URI prefix" being unrecognized. That's the "view-source:" portion of your string.
So, remove that part of the URL and you will have a valid url.
string userInput = "view-source:http://stackoverflow.com/";
string address = userInput.Replace("view-source:", "");
Note: this may produce different results for web apps that provide additional content after javascript has been run and interpreted. You might not ultimately get what you want.
Edit: after your comment, it sounds like you want to remove the possibility of the url starting with "view-source:" which I have reflected in the answer.
Just in case you're looking for the "post javascript" source. There's a project on github that offers this feature but I've never used it. I only know about it because it's maintained by a guy I work with.
You can also find a working example in this repl
I would like to get the exact url that user typed into the browser. Of course I could always use something like Request.Url.ToString() but this does not give me what i want in the following situation:
http://www.mysite.com/rss
With the url above what Request.Url.ToString() would give me is:
http://www.mysite.com/rss/Default.aspx
Does anyone know how to accomplish this?
I have already tried:
Request.Url
Request.RawUrl
this.Request.ServerVariables["CACHE_URL"]
this.Request.ServerVariables["HTTP_URL"]
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "CACHE_URL")
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "HTTP_URL")
Edit: You want the HttpWorkerRequest.GetServerVariable() with the key HTTP_URL or CACHE_URL. Note that the behavior differs between IIS 5 and IIS 6 (see documentation of the keys).
In order to be able to access all server variables (in case you get null), directly access the HttpWorkerRequest:
HttpWorkerRequest workerRequest =
(HttpWorkerRequest)((IServiceProvider)HttpContext.Current)
.GetService(typeof(HttpWorkerRequest));
Remember too that the "exact URL that the user entered" may never be available at the server. Each link in the chain from fingers to server can slightly modify the request.
For example if I type xheo.com into my browser window, IE will be convert to http://www.xheo.com automatically. Then when the request gets to IIS it says to the browser - you really want the default page at http://www.xheo.com/Default.aspx. So the browser responds by asking for the default page.
Same thing happens with HTTP 30x redirect requests. The server will likely only ever see the final request made by the browser.
Try using Request.Url.OriginalString
Might give you the thing you are looking for.
It is possible, you just need to combining a few of the values from the request object to rebuild the exact url entered:
Dim pageUrl As String = String.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Host,
Request.RawUrl)
Response.Write(pageUrl)
Entering the address http://yousite.com/?hello returns exactly:
http://yousite.com/?hello
Request.RawUrl
I think is the monkey you are after...
Easiest way to do this is used client-side programming to extract the exact url:
<script language="javascript" type="text/javascript">
document.write (document.location.href);
</script>
Firstly, this seems like something that should have been asked before, but I cannot find anything that answers my question.
A basic overview of my task is to render an anchor link on a web page which is based on a user defined web address. As the address is user defined this could be in any format, for example:
http://www.example.com
https://www.example.com
www.example.com
example.com
What I need to do with this value is to set it as the href property of an anchor tag. Now, the problem is that (in Chrome at least) only the first two examples will work due to the fact they are recognised as absolute URL paths. The last two examples will redirect to the same domain (i.e. treated as relative paths)
So the ultimate question is: What is the best way to format these values to ensure a consistent absolute path is used? I could check for http/https and add it if missing, but I was hoping there might be an out of the box .Net class that would be more reliable.
In addition, as this is a user defined value, it could be complete junk anyway so a function to validate the URL would be a nice bonus too.
We ran into this problem a few months back, and needed a consistent way of ensuring the URLs were absolute. We also wanted a way of removing http(s):// for displaying the URL on the web page.
I came up with this function:
public static string FormatUrl(string Url, bool IncludeHttp = null)
{
Url = Url.ToLower();
switch (IncludeHttp) {
case true:
if (!(Url.StartsWith("http://") || Url.StartsWith("https://")))
Url = "http://" + Url;
break;
case false:
if (Url.StartsWith("http://"))
Url = Url.Remove(0, "http://".Length);
if (Url.StartsWith("https://"))
Url = Url.Remove(0, "https://".Length);
break;
}
return Url;
}
I know you're after an "out of the box" library, but this may be of some help.
I think the problem with an "out of the box" solution would be that the function won't know whether the URL should be http:// or https://. With my function I've made an assumption that its going to be http://, but for some URLs you need https://. If Microsoft were to build something like this into the framework, it would be buggy from the start.
You can try using this overload of the Uri class:
Uri Constructor (String)
This constructor creates a Uri instance from a URI string. It parses the URI, puts it in canonical format, and makes any required escape encodings.
This constructor does not ensure that the Uri refers to an accessible resource.
This constructor assumes that the string parameter references an absolute URI and is equivalent to calling the Uri constructor with UriKind set to Absolute. If the string parameter passed to the constructor is a relative URI, this constructor will throw a UriFormatException.
This will try to construct a canonical Uri from the user input. And you have lots of properties to check and extract the URL parts that you need.
when url= http://www.iranfairco.com/MainPP.aspx?idCompany=142707090021 .
change content MainPP.aspx by idCompany
for example idCompany=142707090021 equal companyName microsoft
no how can when user enter url: http://www.iranfairco.com/microsoft this equal above url
how can http://www.iranfairco.com/MainPP.aspx?idCompany=142707090021====url:http://www.iranfairco.com/microsoft
You should use some url rewrite module (or write your own - it's not hard).
For example: IIS URL Rewrite, also look here.
Look at also this thourough explanation of how URL Rewriting in ASP.NET works.
I would like to take the original URL, truncate the query string parameters, and return a cleaned up version of the URL. I would like it to occur across the whole application, so performing through the global.asax would be ideal. Also, I think a 301 redirect would be in order as well.
ie.
in: www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media
out: www.website.com/default.aspx
What would be the best way to achieve this?
System.Uri is your friend here. This has many helpful utilities on it, but the one you want is GetLeftPart:
string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
Uri uri = new Uri(url);
Console.WriteLine(uri.GetLeftPart(UriPartial.Path));
This gives the output: http://www.website.com/default.aspx
[The Uri class does require the protocol, http://, to be specified]
GetLeftPart basicallys says "get the left part of the uri up to and including the part I specify". This can be Scheme (just the http:// bit), Authority (the www.website.com part), Path (the /default.aspx) or Query (the querystring).
Assuming you are on an aspx web page, you can then use Response.Redirect(newUrl) to redirect the caller.
Here is a simple trick
Dim uri = New Uri(Request.Url.AbsoluteUri)
dim reqURL = uri.GetLeftPart(UriPartial.Path)
Here is a quick way of getting the root path sans the full path and query.
string path = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,"");
This may look a little better.
string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);
if (rawUrl.Contains("/post/"))
{
bool hasQueryStrings = Request.QueryString.Keys.Count > 1;
if (hasQueryStrings)
{
Uri uri = new Uri(rawUrl);
rawUrl = uri.GetLeftPart(UriPartial.Path);
HtmlLink canonical = new HtmlLink();
canonical.Href = rawUrl;
canonical.Attributes["rel"] = "canonical";
Page.Header.Controls.Add(canonical);
}
}
Followed by a function to properly fetch the application URL.
Works perfectly.
I'm guessing that you want to do this because you want your users to see pretty looking URLs. The only way to get the client to "change" the URL in its address bar is to send it to a new location - i.e. you need to redirect them.
Are the query string parameters going to affect the output of your page? If so, you'll have to look at how to maintain state between requests (session variables, cookies, etc.) because your query string parameters will be lost as soon as you redirect to a page without them.
There are a few ways you can do this globally (in order of preference):
If you have direct control over your server environment then a configurable server module like ISAPI_ReWrite or IIS 7.0 URL Rewrite Module is a great approach.
A custom IHttpModule is a nice, reusable roll-your-own approach.
You can also do this in the global.asax as you suggest
You should only use the 301 response code if the resource has indeed moved permanently. Again, this depends on whether your application needs to use the query string parameters. If you use a permanent redirect a browser (that respects the 301 response code) will skip loading a URL like .../default.aspx?utm_source=twitter&utm_medium=social-media and load .../default.aspx - you'll never even know about the query string parameters.
Finally, you can use POST method requests. This gives you clean URLs and lets you pass parameters in, but will only work with <form> elements or requests you create using JavaScript.
Take a look at the UriBuilder class. You can create one with a url string, and the object will then parse this url and let you access just the elements you desire.
After completing whatever processing you need to do on the query string, just split the url on the question mark:
Dim _CleanUrl as String = Request.Url.AbsoluteUri.Split("?")(0)
Response.Redirect(_CleanUrl)
Granted, my solution is in VB.NET, but I'd imagine that it could be ported over pretty easily. And since we are only looking for the first element of the split, it even "fails" gracefully when there is no querystring.