Request Object not decoding UrlEncoded - asp.net

C#, ASP.NET 3.5
I create a simple URL with an encoded querystring:
string url = "http://localhost/test.aspx?a=" +
Microsoft.JScript.GlobalObject.escape("áíóú");
which becomes nicely: http://localhost/test.aspx?a=%E1%ED%F3%FA (that is good)
When I debug test.aspx I get strange decoding:
string badDecode = Request.QueryString["a"]; //bad
string goodDecode = Request.Url.ToString(); //good
Why would the QueryString not decode the values?

You could try to use HttpServerUtility.UrlEncode instead.
Microsoft documentation on Microsoft.JScript.GlobalObject.escape states that it isn't inteded to be used directly from within your code.
Edit:
As I said in the comments: The two methods encode differently and Request.QueryString expects the encoding used by HttpServerUtility.UrlEncode since it internally uses HttpUtility.UrlDecode.
(HttpServerUtility.UrlEncode actually uses HttpUtility.UrlEncode internally.)
You can easily see the difference between the two methods.
Create a new ASP.NET Web Application, add a reference to Microsoft.JScript then add the following code:
protected void Page_Load(object sender, EventArgs e)
{
var msEncode = Microsoft.JScript.GlobalObject.escape("áíóú");
var httpEncode = Server.UrlEncode("áíóú");
if (Request.QueryString["a"] == null)
{
var url = "/default.aspx?a=" + msEncode + "&b=" + httpEncode;
Response.Redirect(url);
}
else
{
Response.Write(msEncode + "<br />");
Response.Write(httpEncode + "<br /><br />");
Response.Write(Request.QueryString["a"] + "<br />");
Response.Write(Request.QueryString["b"]);
}
}
The result should be:
%E1%ED%F3%FA
%c3%a1%c3%ad%c3%b3%c3%ba
����
áíóú

Related

How do I read all X Headers in asp.net

I want to be able to identify a mobile device using some form of ID.
I read this answer: Get unique, static id from a device via web request about reading x headers in asp.net but when I list all the headers using the following code I don't get any useful x headers
For Each var As String In Request.ServerVariables
Response.Write("<b>" & var & "</b>: " & Request(var) & "<br>")
Next
On my andoid device the only X header I get is HTTP_X_WAP_PROFILE
If you want to read HTTP headers you are going about it the wrong way. ServerVariables only holds some information from the headers.
You should be looking at the Request.Headers property. The following code will list all headers from the HTTP Request. Presumable the "x" headers you refer to will be there..
For Each headerName As String In Request.Headers.AllKeys
Response.Write("<b>" & headerName & "</b>: " & Request.Headers(headerName) & "<br>")
Next
To read the header values you can use the code below.
I thin by using user-agent from which you can get an idea about the browser.
C#
var headers = Request.Headers.ToString();
// If you want it formated in some other way.
var headers = String.Empty;
foreach (var key in Request.Headers.AllKeys)
headers += key + "=" + Request.Headers[key] + Environment.NewLine;
VB.NET:
Dim headers = Request.Headers.ToString()
' If you want it formated in some other way.'
Dim headers As String = String.Empty
For Each key In Request.Headers.AllKeys
headers &= key & "=" & Request.Headers(key) & Environment.NewLine
Next
From Detecting mobile device user agents in ASP.NET (Android):
//for Mobile device
protected override void OnInit(EventArgs e)
{
string userAgent = Request.UserAgent;
if (userAgent.Contains("BlackBerry")
|| (userAgent.Contains("iPhone") || (userAgent.Contains("Android"))))
{
//add css ref to header from code behind
HtmlLink css = new HtmlLink();
css.Href = ResolveClientUrl("~/mobile.css");
css.Attributes["rel"] = "stylesheet";
css.Attributes["type"] = "text/css";
css.Attributes["media"] = "all";
Page.Header.Controls.Add(css);
}
}

How can I pass variables or values from one asp.net vb.net code page to another? [duplicate]

This question already has an answer here:
How can I pass values from one form to another in Asp.net
(1 answer)
Closed 7 years ago.
I have a site/portal created in ASP.net and VB.net.
I want to know how to reference variables between two asp pages, but not the pages themselves, I want to directly transfer data from the .aspx.vb bit of the page to another pages .aspx.vb file. Is that possible?
An easy way in asp.net/VB.net is to use session variables.
Session("myVariable") = "blah"
From another .aspx.vb page you can now use this value. Example:
Dim strTest as String = ""
strTest = Session("myVariable")
You can access this page on any of your .aspx pages for this session by referencing Session("myVariable")
if it's Not sensitive data you can do something like this,
Original page:
protected void Button1_Click(object sender, EventArgs e)
{
string MyOccupation = "Software Developer";
string url;
url = "page2.aspx?occupation=" + MyOccupation;
Response.Redirect(url);
}
Next Page:
string RetrievedValue;protected void Page_Load(object sender, EventArgs e)
{
this.TextBox1.Text = Request.QueryString["occupation"];
RetrievedValue = this.TextBox1.Text;
}
taken from http://forums.asp.net/t/1223291.aspx
Duplicate of How can I pass values from one form to another in Asp.net
Client side technology: Query String
Query String: For SEnding:
string name="abc"; Response.Redirect(" Page2.aspx?name= "+name);
For Getting: On Page2.aspx string name=Response.QueryString.GetValue(" name ");
Server Side Technology:Session
For Setting: Session["Name"] = "Abc";
For Getting: string str = Session["Name"].ToString();
In Session you can pass any object type.
Since nobody posted this, here is Microsoft's page about passing values between pages. It gives C# and VB examples: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

Best way to inject HTML into a page (server-side) in ASP.NET

I've got a HTTPHandler which returns a lump of HTML. What's the best way to inject this into a control on the server?
I've got it mostly working by using an asp:literal and using WebClient.downloadString() to grab the text from the handler
<asp:Literal runat="server" ID="Text_Page1" Visible="false"></asp:Literal>
<asp:Literal runat="server" ID="Text_Page2" Visible="false"></asp:Literal>
and then in the server-side methods:
Text_Page1.Text = new WebClient().DownloadString("http://localhost:666/" +sPage1URL);
Text_Page2.Text = new WebClient().DownloadString("http://localhost:666/" +sPage2URL);
The hardcoded web-address is just there for testing at the moment. Previously I tried just using "~/" +URL to try and build it up but the WebClient library threw an exception saying that the URL was too long (which is not true I don't think)
Any ideas on the best way to do this from the server-side?
Edit : When I say "Best" I mean most efficient and adhering to "best practices". My method doesn't work so well when it's put onto an authenticated IIS. I'm having trouble authenticating. I thought that doing
WebClient oClient = new WebClient();
oClient.Credentials = CredentialCache.DefaultCredentials;
oClient.UseDefaultCredentials = true;
String sData = oClient.DownloadString(sURL);
would work but i get a 401 error. Does anybody have any alternatives?
Cheers
Gordon
Without asking any questions about the reasoning behind fetching html via a webrequest from the same application serving the contents of the include, i would wrap the functionality in a WebUserControl. Something along the lines of:
using System;
using System.Net;
using System.Web.UI;
public partial class HtmlFetcher : UserControl
{
//configure this somewhere else in the real world, web.config maybe
private const string ServiceUrl = "http://localhost:666/";
public string HtmlPath { get; set; }
protected override void Render(HtmlTextWriter output)
{
string outputText = String.Empty;
try
{
outputText = new WebClient().DownloadString(string.Format("{0}{1}", ServiceUrl, HtmlPath));
} catch (Exception e)
{
//Handle that error;
}
output.Write(outputText);
}
}
This is how you would add it to your page:
<%# Register src="HtmlFetcher.ascx" tagname="HtmlFetcher" tagprefix="uc1" %>
<uc1:HtmlFetcher ID="HtmlFetcher1" HtmlPath="some-test-file.html" runat="server" />
you will get the data in the string lcHtml then use it as you want
// *** Establish the request
string lcUrl = "http://yourURL";
HttpWebRequest loHttp =
(HttpWebRequest) WebRequest.Create(lcUrl);
// *** Set properties
loHttp.Timeout = 10000; // 10 secs
loHttp.UserAgent = "Code Sample Web Client";
// *** Retrieve request info headers
HttpWebResponse loWebResponse = (HttpWebResponse) loHttp.GetResponse();
Encoding enc = Encoding.GetEncoding(1252); // Windows default Code Page
StreamReader loResponseStream =
new StreamReader(loWebResponse.GetResponseStream(),enc);
string lcHtml = loResponseStream.ReadToEnd();
loWebResponse.Close();
loResponseStream.Close();
You can use server side code blocks into your aspx with <% %>.
Try this:
<% new WebClient().DownloadString("http://localhost:666/" +sPage1URL) %>

Request Function Returns Null in Firefox/Chrome

I have a several form elements that I am dynamically creating with javascript when a user changes a number value in a textbox, by filling the innerHTML of a div like so:
dfinnerhtml = dfinnerhtml + "<div class='field'> ";
dfinnerhtml = dfinnerhtml + "<textarea name='textbox1" + suffix + "' type='text' id='textbox1" + suffix + "' value='' rows='4' cols='20' class='field'></textarea> ";
dfinnerhtml = dfinnerhtml + "</div> ";
Then, in the aspx.vb code behind, when the user clicks the Save button, I run through a series of Requests to try and add the values that are in these form elements to a SQL string:
Dim DFTestValue1 As String
DFTestValue1 = Request("textbox" & c.ToString)
where c is a loop counter to the # of textboxes created (the input value mentioned above that triggers the create)
The problem here is that this code works in Internet Explorer but not in Firefox or Chrome. The Request() value returns null and nothing is saved. I hope I've explained this well enough.
This post has probably got the answer:
http://forums.asp.net/t/1235816.aspx
Try the PreviousPage property:
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox pTextBox = (TextBox)PreviousPage.FindControl("TextBox1");
Response.Write("Previous Page TextBox: " + pTextBox.Text);
}
}
For anyone that is interested to know, the problem was that a stray tag closed a div that preceded the tag. Internet Explorer didn't seem to care and counted items beyond this point as part of the form.

Read Response.write in another Page

I have a page www.senderdomain.com/sender.aspx, from which i need to write a string to another page in other domain www.receiverdomain.com/receiver.aspx
In sender.aspx i have written
Response.Write("Hello");
Response.Redirect(Request.UrlReferrer.ToString());
It gets redirected to respective receiver.aspx page, but I am not sure how to get the text "Hello" in receiver.aspx page. Can any pl help on this?
It seems you have a value on Sender.aspx that you need to display in receiver.aspx. This is how you can do it.
//On Page_Load of sender.aspx
Session["fromSender"] = "Hello";
Respone.Redirect("receiver.aspx");
Response.End();
//On Page_Load of receiver.aspx
if(!string.IsNullOrEmpty(Session["fromSender"].ToString()))
Response.Write(Session["fromSender"].ToString());
EDIT
In case of change in domain, immediate easy way is to pass the value in query-string.
//On Page_Load of sender.aspx
Response.Redirect("http://www.receiverdomain.com/receiver.aspx?fromSender=Hello");
Response.End();
//On Page_Load of receiver.aspx
if(!string.IsNullOrEmpty(Request.QueryString["fromSender"].ToString()))
Response.Write(Request.QueryString["fromSender"].ToString());
You may observe that the code pattern remains the same and container that is used to transfer the value changes from Session to QueryString.
EDIT2
If security is a concern with you in this case and you don't wish to expose the value ["Hello"], then here comes another way that can help you. In this solution we will first redirect the page to receiver and then from receiver it shall ask for the value to sender. So first we'll write the code for receiver.
//On Page_Load of receiver.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Remember to use System.Net namespace
HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://www.senderdomain.com/sender.aspx?cmd=getvalue");
HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;
//Remember to use System.IO namespace
using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
{
fromSender = responseReader.ReadToEnd();
}
Response.Write(fromSender);
Response.End();
}
}
And in the sender.aspx
//On Page_Load of sender.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["cmd"].ToString()))
{
string cmd = Request.QueryString["cmd"].ToString();
if (cmd.Equals("getvalue", StringComparison.OrdinalIgnoreCase))
{
Response.Clear();
Response.Write("Hello");
Response.End();
}
}
Response.Redirect("http://www.receiverdomain.com/receiver.aspx");
Response.End();
}
}
You need to pass the value in the url or post it in a cross page postback.
For secure cross domain communication, take a look at SAML (Security Assertion Markup Language). It is a standard way of passing information securely across domain boundaries. It is most often used in Single Sign On scenarios, but it can be used to pass data securely. Are you using certificates? What type of encryption are you using?
Another option would be to save state to a database or filesystem that is accessible to both domains.
pass data in query string because can not do like this
for example
Response.Redirect(Request.UrlReferrer.ToString() + "?mytext=hello");
And in receiver page access querystring data, will resolve your issue.
use private algorithm like
string message = "hello";
add 1 to each char so that hello become ifmmp
and on receiver side -1 from each char so it will be hello
The Response.Redirect method will scrap everything that you have written to the page, and replace it with a redirection page, so you can't send any content along with the redirect.
The only option to send data along in a redirect (that works between differnt domains and different servers) is to put it in the URL itself. Example:
string message = "Hello";
Response.Redirect(Request.UrlReferrer.ToString() + "?msg=" + Server.UrlEncode(message));
Another option is to output a page containing a form that is automatically posted to the destination:
string message = "Hello";
Response.Write(
"<html>" +
"<head><title>Redirect</title></head>" +
"<body onload=\"document.forms[0].submit();\">" +
"<form action=\"" + Server.HtmlEncode(Request.UrlReferrer.ToString()) + "\" method=\"post\">" +
"<input type=\"hidden\" name=\"msg\" value=\"" + Server.HtmlEncode(message) + "\">" +
"</form>" +
"</body>" +
"</html>"
);
Response.End();
You can use Request.Form["msg"] on the recieving page to get the value.
Don't use the built-in URL encode, if you want to avoid all sorts of problems later.
String UrlEncode(String value)
{
StringBuilder result = new StringBuilder();
foreach (char symbol in value)
{
if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~".IndexOf(symbol) != -1) result.Append(symbol);
else result.Append("%u" + String.Format("{0:X4}", (int)symbol));
}
return result.ToString();
}
The above supports unicode, and pretty much everything.

Resources