System.Net.WebClient - 使用包含单引号的编码字符串调用 UploadValues 异常
System.Net.WebClient - exception calling UploadValues with encoded string containing single quote
使用包含单引号的编码字符串调用 UploadValues 时出现以下异常:
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.
代码是 运行 ASP.NET MVC 网站的以下操作:
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;
}
}
GetString 操作定义如下:
public class ServicesController : Controller
{
public string GetString(string name)
{
return "Hello " + name;
}
}
如果我删除单引号,方法就会成功。如何将带引号的字符串传递给 UploadValues?
您正在使用 HtmlEncode
,但该值应该是 URL 编码的,因为它将作为 application/www-form-urlencoded 内容上传.
请尝试使用 HttpUtility.UrlEncode
。
使用包含单引号的编码字符串调用 UploadValues 时出现以下异常:
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.
代码是 运行 ASP.NET MVC 网站的以下操作:
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;
}
}
GetString 操作定义如下:
public class ServicesController : Controller
{
public string GetString(string name)
{
return "Hello " + name;
}
}
如果我删除单引号,方法就会成功。如何将带引号的字符串传递给 UploadValues?
您正在使用 HtmlEncode
,但该值应该是 URL 编码的,因为它将作为 application/www-form-urlencoded 内容上传.
请尝试使用 HttpUtility.UrlEncode
。