How to Post Json to a Server Using C#

How to post JSON to a server using C#?

The way I do it and is working is:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"test\"," +
"\"password\":\"bla\"}";

streamWriter.Write(json);
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}

I wrote a library to perform this task in a simpler way, it is here: https://github.com/ademargomes/JsonRequest

Send JSON via POST in C# and Receive the JSON returned?

I found myself using the HttpClient library to query RESTful APIs as the code is very straightforward and fully async'ed. To send this JSON payload:

{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}

With two classes representing the JSON structure you posted that may look like this:

public class Credentials
{
public Agent Agent { get; set; }

public string Username { get; set; }

public string Password { get; set; }

public string Token { get; set; }
}

public class Agent
{
public string Name { get; set; }

public int Version { get; set; }
}

You could have a method like this, which would do your POST request:

var payload = new Credentials { 
Agent = new Agent {
Name = "Agent Name",
Version = 1
},
Username = "Username",
Password = "User Password",
Token = "xxxxx"
};

// Serialize our concrete class into a JSON String
var stringPayload = JsonConvert.SerializeObject(payload);

// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

var httpClient = new HttpClient()

// Do the actual request and await the response
var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);

// If the response contains content we want to read it!
if (httpResponse.Content != null) {
var responseContent = await httpResponse.Content.ReadAsStringAsync();

// From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
}

Send JSON data in http post request C#

try this

using (var client = new HttpClient())
{
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
var baseAddress = "https://....";
var api = "/controller/action";
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(contentType);

var data = new Dictionary<string,string>
{
{"id","72832"},
{"name","John"}
};

var jsonData = JsonConvert.SerializeObject(data);
var contentData = new StringContent(jsonData, Encoding.UTF8, "application/json");

var response = await client.PostAsync(api, contentData);

if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);
}
}

Update

If the request comes back with Json data in the form `

 { "return":"8.00", "name":"John" }

you have to create result model

public class ResultModel
{
public string Name {get; set;}
public double Return {get; set;}
}

and code will be

if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ResultModel>(stringData);

var value=result.Return;
var name=Result.Name;

}

How to post json into HTTP server

With WebApi, you can use something like this:

string url = "http://url.of.server/";
Pedro product = new Pedro();
product.FirtsName = "Ola";
product.ID = 1;
product.Idade = 10;

using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = client.PostAsJsonAsync(url, product).Result;
if (response.IsSuccessStatusCode)
{
// do something
}
}

If you're not using WepApi there are many similar methods, for instance: https://stackoverflow.com/a/39414248/7489072

Don't Base64 encode the body of your post, as suggested in the comments, unless you absolutely must / want to post binary files AND have control over the receiving webserver. Webservers in 99% of the cases expect a plain text body.
If you need to post characters outside the ASCII range, use the correct HTTP headers to specify a Unicode body load.

Update 1 (headers):
The HttpClient class has property DefaultRequestHeaders that can be used to set common request headers, such as AcceptEncoding. If you need a more fine grained control of the content headers, use .PostAsync(string uri, HttpContent content) in stead of .PostAsJsonAsync (that just sets some default headers for Json content)

using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

string stringFromObject = JsonConvert.SerializeObject(product);
HttpContent content = new StringContent(stringFromObject, Encoding.UTF8, "application/json");
content.Headers.Add("YourCustomHeader", "YourParameter");

HttpResponseMessage response = client.PostAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
// do something
}
}

Update 2 (encoding):
To elaborate more on the encoding comments: of course you should escape quotes and the likes. But this is part of the Json standard and should be handled by common encoders / decoders. On top of that, you can use any further encoding for the properties of your serialized object. For instance HTML-encoding on strings and Base64 on binary properties. As long as you know the webserver receiving it will decode it properly.

{ 
"id": 3,
"title": "Decode this",
"description": "this is < HTML encoded >",
"profileImgBase64": "Nzg5MzQ4IHdleWhmQVMmKihFJiphc3R5WUdkdCphc14qVHlpZg0K"
}

So encode individual properties, but don't encode the whole Json payload, as you would have to decode it at the beginning of the receiving pipeline and it's just not something webservers will understand.

How to send a JSon file to the remote web server using C#

I use the following code

    private void btnUploadToServer_Click(object sender, EventArgs e)
{
bool connection = NetworkInterface.GetIsNetworkAvailable();
if (connection == true)
{
//MessageBox.Show("Internet Available");

try
{
using (WebClient client = new WebClient())
{
string filePath = @"C:\Users\SAKTHYBAALAN-PC\Desktop\app_sample.json";
var myUri = new Uri(@"http://your_address/path/file.php");
client.UploadFile(myUri, filePath);
client.Credentials = CredentialCache.DefaultCredentials;
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}

MessageBox.Show("Successfully Uploaded", "Success");
btnExecuteURL.Enabled = true;
}

else
{
MessageBox.Show("There is no internet connection.\n Please make sure that you have an internet connection.", "No Internet");
}
}

upload file on server webfolder and post json data at the same using asp.net web api

Uploading a file from web form to server requires a different approach specially when you want to upload file with other model data.

Files selected on the client can not be submitted as JSON to the server. So we need to submit the form as a Collection to the server. We also can not use application\json as content-type.

Consider following example. The example is demonstrated with ASP.NET MVC application example.

First thing you need to do is add the File object as part of the model class.

public class ClientDocument
{
public int Id {get;set;}
public int ClientId {get;set;}
public string Title {get;set;}
// Below property is used for getting file from client to the server.
public IFormFile File {get;set;}
}

Then you need to create a form in the View. Assume that the view has Model type set to the above class.

<form id="someForm" method="post">
@Html.HiddenFor(m => m.ClientId)
<table>
<tr>
<td>
@Html.LabelFor(m => m.Title)
</td>
<td>
@Html.TextFor(m => m.Title)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(m => m.File)
</td>
<td>
//Following line of code will render file control, where user can select file from the local machine.
@Html.TextBoxFor(m => m.File, new { Type = "file" })
</td>
</tr>
<tr>
<td colspan="2">
<button type="button" onclick="SubmitForm();">Submit</button>
</td>
</tr>
</table>
</form>

Following is the JavaScript code for submitting the form. SubmitForm function in the JavaScript will convert the form to a FormData object.

FormData is a JavaScript object which represents data as a colleciton of Key/value pairs. Once the FormData object is created, we will post it to the server. As I mentioned above we can not use application\json content-type, we need to use multipart/form-data as encodingtype of the payload.

<script>
function SubmitForm() {
if ($("#someForm").valid()) {
var form = $("#someForm")[0];
var data = new FormData(form);

$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "http://www.somedomain.com/api/ClientDocument/Save",
data: data,
processData: false,
contentType: false,
cache: false,
beforeSend: function () {
// show waiting icon.
},
success: function (data) {
//Hiding waiting icon;
//Display the response in the UI.
},
error: function (xhr, status, errorThrown) {
console.log('ERROR : ' + xhr.responseText);
}
});
}
}
</script>

Now at the server end the controller action would look like following.

public IActionResult Save(ClientDocument model)
{
try
{
//Access File Property to save it on server or upload to some storage
var fileObject = model.File;
var tartgetLocation = "D:\\ClientDocuments\\" + fileObject.FileName;

using (var stream = new FileStream(tartgetLocation , FileMode.Create))
{
fileObject.CopyTo(stream);
}

// Write code to save information to database.
}
catch (Exception ex)
{
//Handle Exception
return Json(new {Status= "Failed"});
}

return Json( new {Status= "Success"});
}

I know that this is not the exact answer you might be looking for. But this should give you an idea about how to approach the problem and apply the same technique if applicable in your use case.

C# post json object using httpWebRequst

The example request you show, shows a JSON request body, yet you tell the server in your HttpWebRequest that the incoming content-type is going to be a form post. But then you don't issue a form post, you post one long string:

countryhelloemailaddressworldphone123 // and so on 

Don't use HttpWebRequest in 2021. It's a two decade old API that has more developer-friendly alternatives by now.

Use HttpClient instead, which has convenient (extension) methods for sending and receiving JSON:

var postModel = new
{
country = "...",
emailaddress = "...",
...
};

var client = new HttpClient();

var response = await client.PostAsJsonAsync(postModel);

You need to install the Microsoft.AspNet.WebApi.Client NuGet package for that extension method.

If you insist you must use an HttpWebRequest, which I highly doubt, your question is answered in How to post JSON to a server using C#?, as that question and answer shows how to use that ancient API.

POSTing JsonObject With HttpClient From Web API

With the new version of HttpClient and without the WebApi package it would be:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;

Or if you want it async:

var result = await client.PostAsync(url, content);


Related Topics



Leave a reply



Submit