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!
should definitely be:
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:
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.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 aWebRequestto 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 aWebRequestis 🙂