System.Net.WebUtility.HtmlDecode 似乎无法正常工作

System.Net.WebUtility.HtmlDecode does not appear to work correctly

这是我的客户端(winform c# 桌面)中的代码:

sb.Append("<informedworker>");
sb.Append("<request name=\"Customer\" action=\"GET\" verb=\"*\">");
sb.Append("</request>");
sb.Append("</informedworker>");
Uri url = new Uri("http://192.168.0.6/DATA_START" + System.Net.WebUtility.HtmlEncode(sb.ToString()) + "DATA_END");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
    HttpStatusCode statusCode = ((HttpWebResponse)response).StatusCode;
    string contents = reader.ReadToEnd();
}

这是我服务器应用程序的代码,它是 c# 中的 UWP 应用程序:

StringBuilder request = new StringBuilder();
using (IInputStream input = args.Socket.InputStream)
{
    byte[] data = new byte[BufferSize];
    IBuffer buffer = data.AsBuffer();
    uint dataRead = BufferSize;
    while (dataRead == BufferSize)
    {
        await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
        request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
        dataRead = buffer.Length;
    }                       
}
System.Diagnostics.Debug.WriteLine(System.Net.WebUtility.HtmlDecode(request.ToString()));

这就是结果:

GET /DATA_START<informedworker><request%20name="Customer"%20action="GET"%20verb="*"></request></informedworker>DATA_END HTTP/1.1
Host: 192.168.0.6
Connection: Keep-Alive

如您所见,“<”和“>”已正确转换,但空格仍被读取为 %20??

据我所知,HtmlDecode 方法使用 HtmlEntities static class,其中包含要解码的实体列表。但是没有提到 space 字符。您可能想尝试调用 Uri.UnescapeDataString()。

:)

https://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring(v=vs.110).aspx