How to UrlEncode Plus Sign "+" in QueryString and UrlDecode Plus Symbol in ASP.NET
by
Doug
Updated June 23, 2010
Here's how you can UrlEncode the plus sign (+) in a URL querystring in ASP.NET and then retrieve the plus symbol after UrlDecoding the string.
In this example, I will do a postback and redirect the Server.UrlEncoded string to another page. First we will replace the "+" sign with "%252b" and then Server.UrlEncode the text:
protected void PostButton_Click(object sender, EventArgs e)
{
// replace plus sign "+" with "%252b"
string myTitle = TitleTextBox.Text.Trim().Replace("+", "%252b");
Response.Redirect("~/default.aspx?title=" + Server.UrlEncode(myTitle));
}
Now on the page we redirected to, we will Server.UrlDecode the QueryString and replace "%2b" with the "+" plus symbol:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Get Querystring for Title, if it exists
string pageTitle = Server.UrlDecode(Request.QueryString["title"]);
if (!string.IsNullOrEmpty(pageTitle))
{
// replace encoded plus sign "%2b" with real plus sign +
pageTitle = Regex.Replace(pageTitle, "%2b", "+", RegexOptions.IgnoreCase);
PageTitleTextBox.Text = pageTitle;
}
}
}
So that's a simple technique that you can use to Server.UrlEncode a string that contains the Plus sign and then retrieve the plus symbol after the querystring has been decoded using Server.UrlDecode in ASP.NET and C#.