I have a repeater.Insidea a repeater there is a button.On item Command I try
protected void rptPost_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int contentID = Int32.Parse(e.CommandArgument.ToString());//Its return 1
string host = HttpContext.Current.Request.Url.ToString();//its return http://localhost:1377/Forum.aspx
//string URL = "~/Modules/Forum/PostDetails.aspx?ID=" + contentID +"&BackUrl=" + host;//Need help hear its not work
string URL = "~/Modules/Forum/PostDetails.aspx?ID=" + contentID ;//Its work
Response.Redirect(URL);
}
when I only try to pass ID its work but if I try to pass multipal url one is ID and next is Current Page Url its unable to find page.And gives page not found error.I unable to understand the problem.Passing Url as a parameter is not support or I missing some thing.Thanks.
Here is the solution:
host = HttpUtility.UrlEncode(host)
and here is why it works:
You are passing the host URL as a GET parameter. GET parameters are part of the GET URI for the redirect. URI syntax includes characters with special meanings, in particular you are using colon (:) and slash (/), which have special meaning in a URI string. In almost all cases special characters should not be used as part of your GET parameter data values.
For cases such as yours, where there is a need to include special characters, UrlEncoding was developed. UrlEncoding, or Percent-encoding, substitutes special characters in URIs with values encoded using the percent sign. These escape sequences are automatically converted back to the original special character as part of URI query processing. The HttpUtility class provides the UrlEncode method as a convenient way to escape all special characters in an input string.
Please note that it is a good idea to URL encode all data that you pass via GET parameters unless you have full control over the data being passed and you can guarantee that encoding is not necessary. This can be a security issue because attackers can include new parameters and otherwise manipulate your URI if you pass user input to a GET parameter without first URL encoding it.
Related
I have to download a file (using existing Flurl-Http endpoints [1]) whose name contains a "#" which of course has to be escaped to %23 to not conflict with uri-fragment detection.
But Flurl always escapes the rest but not this character, resulting in a non working uri where half of the path and all query params are missing because they got parsed as uri-fragment:
Url url = "http://server/api";
url.AppendPathSegment("item #123.txt");
Console.WriteLine(url.ToString());
Returns: http://server/api/item%20#123.txt
This means a http request (using Flurl.Http) would only try to download the non-existing resource http://server/api/item%20.
Even when I pre-escape the segment, the result still becomes exactly the same:
url.AppendPathSegment("item %23123.txt");
Console.WriteLine(url.ToString());
Again returns: http://server/api/item%20#123.txt.
Any way to stop this "magic" happen?
[1] This means I have delegates/interfaces where input is an existing Flurl.Url instance which I have to modify.
It looks like you've uncovered a bug. Here are the documented encoding rules Flurl follows:
Query string values are fully URL-encoded.
For path segments, reserved characters such as / and % are not encoded.
For path segments, illegal characters such as spaces are encoded.
For path segments, the ? character is encoded, since query strings get special treatment.
According to the 2nd point, it shouldn't encode # in the path, so how it handles AppendPathSegment("item #123.txt") is correct. However, when you encode the # to %23 yourself, Flurl certainly shouldn't unencode it. But I've confirmed that's what's happening. I invite you to create an issue on GitHub and it'll be addressed.
In the mean time, you could write your own extension method to cover this case. Something like this should work (and you wouldn't even need to pre-encode #):
public static Url AppendFileName(this Url url, string fileName) {
url.Path += "/" + WebUtility.UrlEncode(fileName);
return url;
}
I ended up using Uri.EscapeDataString(foo) because suggested WebUtility.UrlEncode replaces space with '+' which I didn't want to.
My site throws an exception every time a special kind of character is included in the request, or when the size of the URL exceeds a certain length.
How can I control the URL and transform it before processing it (For example : if the request was http://xwz.com/"ert I want to turn it into http://xwz.com/ert). Something like that.
I am using .net and c#
use this : HttpServerUtility.UrlEncode Method (String)
You can use it like this :
System.Web.HttpUtility.UrlEncode("test t");
You will need this library : UrlEncode usesSystem.Web.HttpUtility.UrlEncodeto encode strings.
Looking for HttpUtility.UrlEncode
The UrlEncode(String) method can be used to encode the entire URL, including query-string values. If characters such as blanks and punctuation are passed in an HTTP stream without encoding, they might be misinterpreted at the receiving end. URL encoding converts characters that are not allowed in a URL into character-entity equivalents; URL decoding reverses the encoding. For example, when the characters < and > are embedded in a block of text to be transmitted in a URL, they are encoded as %3c and %3e.
The code below will replace any invalid characters in your URL by an empty space
string url = System.Text.RegularExpressions.Regex.Replace(url , #"/^[!#$&-;=?-[]_a-z~]+$/", "");
I think this is what you're looking for:
System.Web.HttpUtility.UrlEncode(string url)
i have an ashx file that requires some query-string values to deliver appropriate images.
The problem is some search engines urlencode then htmlencode those urls in their cache or when they index those.
So for example instead of getting
/preview.ashx?file=abcd.jpg&root=small
i get
/preview.ashx?file=abcd.jpg&root=small
this basically throws off the context.Request.QueryString["root"] so it thinks that there's no variable root
i guess the second key in the querystring is amp;root i.e the part after the & sign.
What i'm wondering is if there's a way to automatically html and urldecode the querystring on serverside so that the program doesn't get confused.
There is no harm in calling HttpUtility.HtmlDecode or HttpUtility.UrlDecode more than once.
string queryString = "/preview.ashx?file=abcd.jpg&root=small";
var parsedString = HttpUtility.HtmlDecode(queryString);
var root = HttpUtility.ParseQueryString(parsedString)["root"];
To URL encode and decode you can use the following methods:
string encoded = System.Web.HttpUtility.UrlEncode(url);
string decoded = System.Web.HttpUtility.UrlDecode(url);
I've seen instances in the past where the Query String has been doubly encoded. In which case you'll need to doubly decode — this may be your issue...
this is my first post on stackoverlow and I couldn't find a solution to this in any other posts, so here it goes:
I have a web page that is sending two query strings in the url:
example.aspx?name=<%=name%>&sku=<%=sku%>
I then collect the values using Request.QueryString["name"]; and Request.QueryString["sku"];
When I view the url on the source of the page sending the query strings everything looks fine, but if "name" contains a forward slash (/) it will somehow get tacked on to the end of "sku" when I retrieve the value of the query string. I've tried to replace the / with %2F but that doesn't work. If the "name" query string doesn't have a slash everything looks correct.
Any Ideas?
Edit: I ended up having to double encode (server.urlencode) and double decode for it to work correctly. Thanks for all your help!
Actually, your should encode your values for URLs with HttpServerUtility.UrlEncode method:
example.aspx?name=<%=Server.UrlEncode(name)%>&sku=<%=Server.UrlEncode(sku)%>
URL encoding ensures that all browsers
will correctly transmit text in URL
strings. Characters such as a question
mark (?), ampersand (&), slash mark
(/), and spaces might be truncated or
corrupted by some browsers. As a
result, these characters must be
encoded in tags or in query
strings where the strings can be
re-sent by a browser in a request
string.
EDIT:
let's check this with the values you provided:
name = Bellagio™ 16 1/2" High Downbridge Outdoor Wall Light,
sku = 46910: firstly I created a page with 2 properties:
public string Name
{
get
{
return "Bellagio™ 16 1/2\" High Downbridge Outdoor Wall Light";
}
}
public string Sku
{
get
{
return "46910";
}
}
and then add link definition to the page:
<a href='1.aspx?name=<%=Server.UrlEncode(Name)%>&sku=<%=Server.UrlEncode(Sku)%>'>
this is a link
</a>
and then grab these values (click the link firstly):
protected void Page_Load(object sender, EventArgs e)
{
var name = Request.QueryString["name"];
var sku = Request.QueryString["sku"];
}
these values are exactly the same as you provided: Bellagio™ 16 1/2\" High Downbridge Outdoor Wall Light and 46910.
Unfortunatelly, I was unable to reproduce an incorrect URL you post in your first comment: LifeSizePDF.aspx?productname=Bellagio&%238482%3b+16+1%2f2"%3b+High+Downbridge+Outdoor+Wall+Light&shortsku=46910%2f
Use URL encoding to format the values appropriately, assuming the forward slash in the name is intentional and would like to be extracted with the end result.
Note that there are at least two ways to go about this easily, for example using the static class HttpUtility or, when in the context of a Page, using the Server property:
var encodedValue = HttpUtility.UrlEncode(rawValue);
var encodedValue = Server.UrlEncode(rawValue);
You could just trim the end value of the sku request:
Request.QueryString["sku"].TrimEnd( '/' );
When I run my project I get the url http://localhost:5973/PageToPageValuePass/Default.aspx I want to Encode the URL since sometimes I need to transfer data from page to page. When the urls are encoded then it increases the reliability.
Server.UrlEncode("http://www.google.com/c#");
I get this, but how do I use it to help me encode the url?
If your encoding parts of the path:
System.Uri.EscapeUriString("c#")
If your encoding 'arguments':
String.Format( "http://something/?test={0}", System.Uri.EscapeDataString("c#") );
try this
in ASP.NET
Server.UrlEncode("http://www.google.com/c#");
in WinForms using System.Web.dll
HttpUtility.UrlEncode("http://www.google.com/c#");
Url encoding is used to ensure that special symbols included in a url (most likely in a querystring) are not mistakenly interpreted as those used in the parsing and processing of a url. For example, the + symbol is used to indicate a space in a url. However, if you were intending for a + symbol to be a part of your querystring then you would want to encode that querystring before sending it to a browser.
For example. Imagine you have written a page that receives a math equation on the querystring and displays that equation on the page.
The url might be: http://yoursite.com/displayMath.aspx?equation=3+5
The + symbol in this case is intended to be a meaningful part of the equation. However, without a UrlEncode it would be interpreted as representing a space. Reading this value from the querystring on the receiving page would yield "3 5", which is not what was intended.
Instead of redirecting to that url directly, you would want to URL encode the request first. You might write the following code:
string equation = "3+5";
string url = String.Format(#"http://yoursite.com/displayMath.aspx?equation={0}", equation);
string encodedUrl = Server.UrlEncode(url);
Response.Redirect(encodedUrl);
This would ensure that a subsequent Request.Querystring["equation"] would receive the equation intact because any special symbols would first be encoded.
I'm not sure I understand your use case for encoding urls. If you could perhaps provide more information on what you are trying to achieve I will attempt to answer more fully. For now I hope that this information is useful.
say you want to create a link with some parameters you can use it as follows:
aspx:
Click Here
code behind:
myLink.Href = Page.ResolveClientUrl("~/MyPage.aspx") + "?id=" +
Server.UrlEncode("put here what ever you want to url encode");
Or as in your question:
myLink.Href = "http://www.google.com/")+Server.UrlEncode("C#");
this will put in html:
<a id="myLink" runat="server" target="_self" href="http://www.google.com/c+c%23">