如何使用 C# 将 JSON 发布到服务器?
这是我正在使用的代码:
// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(json);
// this is important - make sure you specify type this way
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json";
request.ContentLength = postBytes.Length;
request.CookieContainer = Cookies;
request.UserAgent = currentUserAgent;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// grab te response and print it out to the console along with the status code
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result;
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
result = rdr.ReadToEnd();
}
return result;
当我运行此代码时,我总是收到 500 内部服务器错误。
我做错了什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
我这样做和工作的方式是:
我编写了一个库来以更简单的方式执行此任务,它在这里: https://github.com/ademargomes/JsonRequest
The way I do it and is working is:
I wrote a library to perform this task in a simpler way, it is here: https://github.com/ademargomes/JsonRequest
Ademar 的解决方案可以通过利用
JavaScriptSerializer
的Serialize
方法来改进,以提供对象到 JSON 的隐式转换。此外,还可以利用
using
语句的默认功能来省略显式调用Flush
和Close
。Ademar's solution can be improved by leveraging
JavaScriptSerializer
'sSerialize
method to provide implicit conversion of the object to JSON.Additionally, it is possible to leverage the
using
statement's default functionality in order to omit explicitly callingFlush
andClose
.HttpClient
类型是较新的类型实现优于WebClient
和HttpWebRequest
。WebClient
和WebRequest
均已被标记为过时。 [1]您只需使用以下几行。
当您多次需要
HttpClient
时,建议仅创建一个实例并重用它或使用新的HttpClientFactory
。 [2]@learn.microsoft.com [3]
自 dotnet core 3.1 您可以使用
JsonSerializer
来自System.Text.Json
创建 json 字符串。The
HttpClient
type is a newer implementation than theWebClient
andHttpWebRequest
. Both theWebClient
andWebRequest
have been marked as obsolete. [1]You can simply use the following lines.
When you need your
HttpClient
more than once it's recommended to only create one instance and reuse it or use the newHttpClientFactory
. [2]@learn.microsoft.com [3]
Since dotnet core 3.1 you can use the
JsonSerializer
fromSystem.Text.Json
to create your json string.根据 Sean 的帖子,没有必要嵌套 using 语句。通过
使用
StreamWriter,它将在块末尾刷新并关闭,因此无需显式调用Flush()
和Close()
方法:Further to Sean's post, it isn't necessary to nest the using statements. By
using
the StreamWriter it will be flushed and closed at the end of the block so no need to explicitly call theFlush()
andClose()
methods:如果您需要异步调用,请使用
If you need to call is asynchronously then use
我最近想出了一种更简单的方法来发布 JSON,其中包括从应用程序中的模型进行转换的附加步骤。请注意,您必须为控制器创建模型
[JsonObject]
才能获取值并进行转换。请求:
模型:
服务器端:
I recently came up with a much simpler way to post a JSON, with the additional step of converting from a model in my app. Note that you have to make the model
[JsonObject]
for your controller to get the values and do the conversion.Request:
Model:
Server side:
注意您正在使用的内容类型:
来源:
RFC4627
其他帖子
Take care of the Content-Type you are using :
Sources :
RFC4627
Other post
到 .Net 4.5.1 此选项 可以工作:
Up to .Net 4.5.1 this option can work:
警告!我对此主题有非常强烈的看法。
.NET 现有的 Web 客户端对开发人员不友好! WebRequest & WebClient 是“如何让开发人员感到沮丧”的主要示例”。它们很冗长且冗长。操作复杂;当您只想用 C# 发送一个简单的 Post 请求时。 HttpClient 在解决这些问题方面有所作为,但它仍然存在不足。最重要的是,微软的文档很糟糕……真的很糟糕;除非你想筛选一页又一页的技术简介。
开源来救援。有三个优秀的开源、免费 NuGet 库作为替代方案。谢天谢地!这些都得到了很好的支持和记录,是的,很容易修正……超级容易使用。
它们之间没有太多区别,但我认为 ServiceStack.Text 稍占优势……
好的 - 那么 JSON 格式的 Post 请求在 ServiceStack.Text 中是什么样子的?
这是一行代码。简洁&简单的!将以上内容与 .NET 的 Http 库进行比较。
WARNING! I have a very strong view on this subject.
.NET’s existing web clients are not developer friendly! WebRequest & WebClient are prime examples of "how to frustrate a developer". They are verbose & complicated to work with; when all you want to do is a simple Post request in C#. HttpClient goes some way in addressing these issues, but it still falls short. On top of that Microsoft’s documentation is bad … really bad; unless you want to sift through pages and pages of technical blurb.
Open-source to the rescue. There are three excellent open-source, free NuGet libraries as alternatives. Thank goodness! These are all well supported, documented and yes, easy - correction…super easy - to work with.
There is not much between them, but I would give ServiceStack.Text the slight edge …
Ok - so what does a Post Request in JSON look like within ServiceStack.Text?
That is one line of code. Concise & easy! Compare the above to .NET’s Http libraries.
实现此目的的一些不同且干净的方法是使用 HttpClient,如下所示:
Some different and clean way to achieve this is by using HttpClient like this:
我最终通过包含 .Result 在同步模式下调用
I finally invoked in sync mode by including the .Result
我发现这是发布读取的 JSON 数据的最友好、最简洁的方式:
我使用 Microsoft 的 System.Text.Json 来序列化和反序列化 JSON。请参阅 NuGet。
I find this to be the friendliest and most concise way to post an read JSON data:
I'm using Microsoft's
System.Text.Json
for serializing and deserializing JSON. See NuGet.我就是这样做的
This is how I do it
Dot net core 解决方案
首先使用 Newtonsoft.Json,然后编写如下方法:
该方法返回 string。如果您想将
string
结果反序列化为JSON
,只需在方法末尾添加此行:其中
LoginTokenResponse
是您的自定义类想要反序列化字符串结果Dot net core solution
first using
Newtonsoft.Json
then write a method like this:This method return
string
. if you want to deserialize thestring
result toJSON
, simply add this line at the end of the method:Which
LoginTokenResponse
is the custom class you want to Deserialize the string resultvar data = Encoding.ASCII.GetBytes(json);
byte[] postBytes = Encoding.UTF8.GetBytes(json);
使用 ASCII 而不是 UFT8
var data = Encoding.ASCII.GetBytes(json);
byte[] postBytes = Encoding.UTF8.GetBytes(json);
Use ASCII instead of UFT8