Asp.net Urldecode QueryString
Many Asp.net web developers assumes that, if QueryString parameter is in encoded format then it should be decoded before processing the data. This is really one of the wrong assumption. Here I will explain what's the correct way to deal with QueryString parameters.
Before passing the parameter to http web request, it has to be encoded. Otherwise, your request would get terminated.
Encodong of the parameter is done by HttpUtility.UrlEncode function.
Asp.net UrlDecode for QueryString parameter example.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class URLEncodeDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string math = Request.QueryString["result"];
Response.Write("Output is: " + math);
Response.Write("
");
Response.Write("Output using UrlDecode is: " + HttpUtility.UrlDecode(Request.QueryString["result"]));
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect(Request.Url.ToString() + "?result=" + HttpUtility.UrlEncode("12+25"));
}
}
output
http://localhost:3716/web.Demo/URLEncodeDemo.aspx?result=12%2b25
Output is: 12+25
Output using UrlDecode is: 12 25
Description Here we are expecting to get "12+25", which is what we had passed as query string parameter. QueryString method itself decode the parameters, so you don't need to decode it explicitly.
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5