【问题标题】:HttpWebRequest POST adds a NULL value to Form VariablesHttpWebRequest POST 向表单变量添加 NULL 值
【发布时间】:2011-01-10 22:20:58
【问题描述】:

我正在尝试通过 POST 使用 HttpWebRequest 对象调用 RESTful 服务。我正在尝试使用包含 url 编码字符串的请求正文传递 1 个变量。当它到达服务器时,我看到了请求;但是,它显示了 2 个表单变量。第一个是 Form[null],第二个是我的变量。

我正在尝试定位这个 NULL 键的来源;但是,我不能。关于如何解决这个问题的任何想法,因为当我尝试将它与 .Net 的 Nancy Web 框架一起使用时会引发问题。

代码:

var request = WebRequest.Create("http://localhost:8888/RouteName") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

var jsonString =
    "[\"00000000-0000-0000-000000000001\",\"00000000-0000-0000-000000000002\"]";

var data = new StringBuilder();
data.Append("Keys=" + HttpUtility.UrlEncode(jsonString));

byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;

using (var requestStream = request.GetRequestStream())
{
    requestStream.Write(byteData, 0, byteData.Length);
}

using (var response = request.GetResponse() as HttpWebResponse)
{
    // ends up with a 500 response.
}

【问题讨论】:

    标签: c# asp.net httpwebrequest


    【解决方案1】:

    我没有大量使用 Webrequest,主要是因为我发现 webclient 对我来说更容易使用。 下面是一个使用 Webclient 通过 POST 发送数据的简单示例:

    class Program
    {
        static void Main(string[] args)
        {
            var webclient = new WebClient();
            var valueToSend = new Message("some data", "some other data");
            var parameters = new NameValueCollection 
              {
                {"Key", Jsonify(valueToSend)}
              };
            webclient.UploadValues(
              "http://localhost:8888/Ny", 
              "POST", 
              parameters);
        }
    
        static string Jsonify(object data)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                var ser = new DataContractJsonSerializer(data.GetType());
                ser.WriteObject(ms,data);
                return Encoding.Default.GetString(ms.ToArray());
            }
        }
    
    }
    

    这可能不是您所寻找的,但它消除了许多潜在的错误来源。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      相关资源
      最近更新 更多