开发者

HttpWebRequest POST adds a NULL value to Form Variables

I am attempting to call a RESTful service using an HttpWebRequest object via POST. I am attempting to pass 1 variable with the Request body which contains a url enco开发者_高级运维ded string. I see the request when it hits the server; however, it shows 2 form variables. The first is Form[null] and the second is my variable.

I am attempting to locate the source of this NULL key; however, I cannot. Any ideas on how I may be able to remedy this since it's throwing issues when I attempt to use it with the Nancy web framework for .Net.

Code:

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.
}


I have not used Webrequest to a great extent, mostly because I find webclient to me so much easier to use. Here is a quick example using Webclient to send data using 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());
        }
    }

}

This migth not be quite what you where looking for, but it takes away many potential error sources.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜