user523234 user523234 - 1 month ago 15
ASP.NET (C#) Question

How to encode the plus (+) symbol in URL

The URL link below will open a new Google mail window. The problem I have is that Google replaces all the plus (+) sign in the email body with blank space. It looks like it only happens with the + sign. Any suggestions on how to remedy this? ( I am working the ASP.NET web page)

https://mail.google.com/mail?view=cm&tf=0&to=someemail@somedomain.com&su=some subject&body=Hi there+Hello there

(In the body email, "Hi there+Hello there" will show up as "Hi there Hello there")

Answer

The + character has a special meaning in a url => it means whitespace. If you want to use the + sign you need to URL encode it:

body=Hi+there%2bHello+there

Here's an example of how you could properly generate urls in .NET:

class Program
{
    static void Main()
    {
        var uriBuilder = new UriBuilder("https://mail.google.com/mail");
        var values = HttpUtility.ParseQueryString(string.Empty);
        values["view"] = "cm";
        values["tf"] = "0";
        values["to"] = "someemail@somedomain.com";
        values["su"] = "some subject";
        values["body"] = "Hi there+Hello there";
        uriBuilder.Query = values.ToString();
        var url = uriBuilder.ToString();
        Console.WriteLine(url);
    }
}
Comments