将值传递给在C#中PUT请求JSON [英] Passing values to a PUT JSON Request in C#

查看:173
本文介绍了将值传递给在C#中PUT请求JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API工作,并尝试做C#中的JSON PUT请求。这是我使用的代码:

 公共静态布尔SendAnSMSMessage()
{
变种的HttpWebRequest = (HttpWebRequest的)WebRequest.Create(https://开头apiURL);
httpWebRequest.ContentType =文/ JSON;
httpWebRequest.Method =PUT;

使用(VAR的StreamWriter =新的StreamWriter(httpWebRequest.GetRequestStream()))
{
JSON字符串** = //需要把这里的数据传递给API。 **

streamWriter.Write(JSON);
}
VAR的HttpResponse =(HttpWebResponse)httpWebRequest.GetResponse();
使用(VAR的StreamReader =新的StreamReader(httpResponse.GetResponseStream()))
{
变种的responseText = streamReader.ReadToEnd();
//现在你有你的回应。
//或虚假取决于响应
返回真实信息;
}
}



问题是我无法弄清楚如何将数据传递给API。所以像在JavaScript中我会做这样的事情来传递数据:

 键入:把',
数据:{'reg_FirstName':'鲍勃',
'reg_LastName':'这家伙,
'reg_Phone':'123-342-1211',
'reg_Email':'someemail @ emai.com',
'reg_Company':'无',
'reg_Address1:有些地方博士,
'reg_Address2':'',
'reg_City': '火星',
'reg_State:GA,
'reg_Zip':'12121',
'reg_Country':'美国'

我怎么会去在C#中做同样的? !谢谢


解决方案

  httpWebRequest.ContentType =文/ JSON; 



绝对应该是:



  httpWebRequest.ContentType =应用/ JSON; 



除此之外,我看不出什么错了你当前的代码。



至于JSON产生部分而言,你可以使用的 JSON序列

  VAR串=新的JavaScriptSerializer() ; 

JSON字符串= serializer.Serialize(新
{
reg_FirstName =鲍勃,
reg_LastName =那家伙,
...和等课程
})的;

在这个例子中我已经很明显使用了匿名对象,但你可以完全正常定义的属性相匹配的模式然后通过这个模型的实例在序列化方法。您可能还需要签出 Json.NET 库,是一个第三方JSON序列比内置的重量更轻,速度更快。 。NET






但一切都这样说,你也可能听说过的的ASP.NET Web API 以及即将到来的.NET 4.5。如果你做了,你应该知道会有一个API HTTP web客户端(的 的HttpClient ),这是专门为那些需求量身定做。使用的WebRequest 消耗JSON支持API将被视为在几个月的陈旧的代码。我提这个,因为你可以使用的NuGet现在使用这个新的客户端,简化了可怜的人(负责移植代码到.NET XX),将看看你的代码,从现在开始,可能一两年的寿命甚至不知道什么是的WebRequest 是: - )


I am working with an API and trying to do a JSON PUT request within C#. This is the code I am using:

    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:

        type: 'PUT',
        data: { 'reg_FirstName': 'Bob',
                'reg_LastName': 'The Guy',
                'reg_Phone': '123-342-1211',
                'reg_Email': 'someemail@emai.com',
                '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!

解决方案

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:

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 Serialize method. You might also want to checkout the Json.NET library which is a third party JSON serializer which is lighter and faster than the built-in .NET.


But all being said, you might also have heard of the ASP.NET Web API as 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 WebRequest to 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 WebRequest is :-)

这篇关于将值传递给在C#中PUT请求JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆