I get the following exception when calling UploadValues with an encoded string containing a single quote:
An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code
Additional information: The remote server returned an error: (500) Internal Server Error.
The code is running in the following action of an ASP.NET MVC web site:
public class HomeController : Controller
{
public string Index()
{
var welcomeMessage = string.Empty;
using (var client = new WebClient())
{
var encodedName = HttpUtility.HtmlEncode("Dave's");
var nameValue = new NameValueCollection { { "name", encodedName } };
var result = client.UploadValues("http://localhost:54011/Services/GetString", nameValue);
welcomeMessage = System.Text.Encoding.UTF8.GetString(result);
}
return welcomeMessage;
}
}
The GetString action is defined like this:
public class ServicesController : Controller
{
public string GetString(string name)
{
return "Hello " + name;
}
}
If I remove the single quote the method succeeds. How can I pass a string with quotes to UploadValues?
You're using HtmlEncode
, but the value should be URL-encoded, as it will be uploaded as application/www-form-urlencoded content.
Try using HttpUtility.UrlEncode
instead.
See more on this question at Stackoverflow