HttpWebRequest POST 将 NULL 值添加到表单变量
我试图通过 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.
}
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 encoded 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.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我没有在很大程度上使用 Webrequest,主要是因为我发现 webclient 对我来说更容易使用。
下面是一个使用 Webclient 通过 POST 发送数据的简单示例:
这可能不是您想要的,但它消除了许多潜在的错误源。
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:
This migth not be quite what you where looking for, but it takes away many potential error sources.