2015-09-04 19 views
0

我得到調用包含一個單引號的編碼字符串UploadValues當出現以下異常:System.Net.WebClient - 異常調用帶有編碼的字符串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.

的代碼在下面的動作運行

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; 
    } 
} 
的ASP.NET MVC網站

如果刪除單引號,則方法成功。我如何傳遞帶有引號的字符串到UploadValues?

回答

1

您使用HtmlEncode,但該值應該是URL -encoded,因爲它會被上傳的應用程序/ WWW的形式進行了urlencoded的內容。

嘗試使用HttpUtility.UrlEncode代替。