在 C# 中将值传递给 PUT JSON 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11248935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing values to a PUT JSON Request in C#
提问by
I am working with an API and trying to do a JSON PUT request within C#. This is the code I am using:
我正在使用 API 并尝试在 C# 中执行 JSON PUT 请求。这是我正在使用的代码:
public static bool SendAnSMSMessage()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://apiURL");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "PUT";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = **// Need to put data here to pass to the API.**
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
The problem is I can't figure out how to pass the data to the API. So like in JavaScript I would do something like this to pass the data:
问题是我不知道如何将数据传递给 API。所以就像在 JavaScript 中一样,我会做这样的事情来传递数据:
type: 'PUT',
data: { 'reg_FirstName': 'Bob',
'reg_LastName': 'The Guy',
'reg_Phone': '123-342-1211',
'reg_Email': '[email protected]',
'reg_Company': 'None',
'reg_Address1': 'Some place Dr',
'reg_Address2': '',
'reg_City': 'Mars',
'reg_State': 'GA',
'reg_Zip': '12121',
'reg_Country': 'United States'
How would I go about doing the same in C#? Thanks!
我将如何在 C# 中做同样的事情?谢谢!
采纳答案by Darin Dimitrov
httpWebRequest.ContentType = "text/json";
should definitely be:
绝对应该是:
httpWebRequest.ContentType = "application/json";
Other than that I don't see anything wrong with your current code.
除此之外,我认为您当前的代码没有任何问题。
As far as the JSON generation part is concerned you could use a JSON serializer:
就 JSON 生成部分而言,您可以使用JSON 序列化程序:
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
reg_FirstName = "Bob",
reg_LastName = "The Guy",
... and so on of course
});
In this example I have obviously used an anonymous object but you could perfectly fine define a model whose properties match and then pass an instance of this model to the Serializemethod. You might also want to checkout the Json.NETlibrary which is a third party JSON serializer which is lighter and faster than the built-in .NET.
在这个例子中,我显然使用了一个匿名对象,但你可以完美地定义一个属性匹配的模型,然后将该模型的一个实例传递给该Serialize方法。您可能还想查看Json.NET库,它是第三方 JSON 序列化程序,它比内置的 .NET 更轻、更快。
But all being said, you might also have heard of the ASP.NET Web APIas well as the upcoming .NET 4.5. If you did, you should be aware that there will be an API HTTP web client (HttpClient) which is specifically tailored for those needs. Using a WebRequestto consume a JSON enabled API will be considered as obsolete code in a couple of months. I am mentioning this because you could use the NuGet to use this new client right now and simplify the life of the poor soul (tasked to migrate your code to .NET X.X) that will look at your code a couple of years from now and probably wouldn't even know what a WebRequestis :-)
但话虽如此,您可能还听说过ASP.NET Web API以及即将推出的 .NET 4.5。如果您这样做了,您应该知道将有一个 API HTTP Web 客户端 ( HttpClient) 专门针对这些需求量身定制。使用 aWebRequest来使用支持 JSON 的 API 将在几个月内被视为过时的代码。我之所以提到这一点,是因为您现在可以使用 NuGet 来使用这个新客户端,并简化将在几年后查看您的代码的可怜人的生活(负责将您的代码迁移到 .NET XX)甚至不知道 aWebRequest是什么:-)
回答by Hintee
If you want to mimic the JavaScript behavior from a .NET C# Client you must also set a few additional configs on the Request object, apart from ContentType, here is a working example:
如果你想从 .NET C# 客户端模仿 JavaScript 行为,你还必须在请求对象上设置一些额外的配置,除了 ContentType,这里是一个工作示例:
string serializedObject = Newtonsoft.Json.JsonConvert.SerializeObject(entity);
HttpWebRequest request = WebRequest.CreateHttp(storeUrl);
request.Method = "PUT";
request.AllowWriteStreamBuffering = false;
request.ContentType = "application/json";
request.Accept = "Accept=application/json";
request.SendChunked = false;
request.ContentLength = serializedObject.Length;
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(serializedObject);
}
var response = request.GetResponse() as HttpWebResponse;
This way the full content will be sent along with the request, therefore the ASP.NET MVC WebAPI data binders can work their magic.
这样,完整的内容将与请求一起发送,因此 ASP.NET MVC WebAPI 数据绑定器可以发挥其魔力。
Needless to say you should be careful on the content size as it will be sent all at once, not streamed/chunk-ed.
毋庸置疑,您应该注意内容大小,因为它将一次发送,而不是流式传输/分块发送。

