How to send json request body data in POST request using C# - c#

I am New in C#.
I want to send JSON request body in POST request using C#.
I want To get results from Rest URL but it's showing me status code 500.
How can I format the request body so that I able to get results from the rest URL?
My Request body in JSON -->
{"filter":{"labtestName":[{"labtestName":"Ada"}]}}
code that I tried
string data1 = "{\filter\":{\"labtestName\":[{\"labtestName\":\"Ada\"}]}}";
var RestURL = "https://nort.co.net/v1api/LabTest/Hurlabtest";
HttpClient client = new HttpClient();
string jsonData = JsonConvert.SerializeObject(data1);
client.BaseAddress = new Uri(RestURL);
StringContent content1 = new StringContent(jsonData, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("apptoken", "72f303a7-f1f0-45a0-ad2b-e6db29328b1a");
client.DefaultRequestHeaders.Add("usertoken", "cZJqFMitFdVz5MOvRLT7baVTJa+yZffc5eVoU91OqkMYl6//cQmgIVkHOyRZ7rWTXi66WV4tMEuj+0oHIyPS6hBvPUY5/RJ7oWnTr4LuzlKU1H7Cp68za57O9AatAJJHiVPowlXwoPUohqe8Ad2u0A==");
HttpResponseMessage response = await client.PostAsync(RestURL, content1);
var result = await response.Content.ReadAsStringAsync();
var responseData = JsonConvert.DeserializeObject<LabtestResponseData>(result);

You are sending the wrong data to the method,
I have corrected it, you can refer to the below code.
myData string is already a JSON string so there is no need to serialize it again.
string myData = "{\"filter\": {\"labtestName\": [{\"labtestName\": \"Ada\"}]}}";
//string data1 = "{\filter\": {\"labtestName\": [{\"labtestName\": \"Ada\"}]}}";
var RestURL = "https://tcdevapi.iworktech.net/v1api/LabTest/HSCLabTests";
HttpClient client = new HttpClient();
//string jsonData = JsonConvert.SerializeObject(myData);
client.BaseAddress = new Uri(RestURL);
StringContent content1 = new StringContent(myData, Encoding.UTF8, "application/json");

Related

How to pass Json Content in request Body Using http client with DeleteAsync Method (C#)?

Need to pass Json Content in Request body using http client DeleAsync Method in C#.Not able to pass the Request body in DeleteAsync Method.
HttpClient client=new HttpClient();
var Ids = new[] { 100,202,304,866 };
string endpoint=" URL goes here";
string jsonString = JsonConvert.SerializeObject(Ids);
var RequestBody = new StringContent(jsonString, Encoding.UTF8);
var response = client.DeleteAsync(endpoint,RequestBody).Result;
You can do like this. As far as I know you can't have body in DeleteAsync
object jsonObj;
using (HttpClient client = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Delete,
RequestUri = new Uri("yourUrl"),
Content = new StringContent(JsonConvert.SerializeObject(jsonObj), Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);

HttpClient request no response

I am not getting any response - no error, no bad request status, etc. - when I send a post request to this API route. postData is simply a JSON object. The funny thing here is this: When i send post data as a string instead of an object, I can get a response.
View the code below:
[HttpPost]
[Route("api/updateStaffs/")]
public async Task<object> UpdateStaff([FromBody] object postData)
{
string _apiUrl = "http://localhost:5000/system/getToken";
string _baseAddress = "http://localhost:5000/system/getToken";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var responseMessage = await client.PostAsync(_apiUrl, new StringContent(postData.ToString(), Encoding.UTF8, "application/json"));
if (responseMessage.IsSuccessStatusCode)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = responseMessage.Content;
return ResponseMessage(response);
}
}
return NotFound();
}
No response:
var postData = new {
user = "test"
pass = "hey"
};
var responseMessage = await client.PostAsync(_apiUrl, new StringContent(postData.ToString(), Encoding.UTF8, "application/json"));
OR
var responseMessage = await client.PostAsync(_apiUrl, new StringContent("{}", Encoding.UTF8, "application/json"));
Will get response:
var responseMessage = await client.PostAsync(_apiUrl, new StringContent("blahblah", Encoding.UTF8, "application/json"));
The receiving API is a third-party application so I am unable to verify if this error is on the other end.
Thanks.
If you dont want to use PostAsJsonAsync
You need to serialize your anonymous type to JSON, the most common tool for this is Json.NET
var jsonData = JsonConvert.SerializeObject(postData);
Then you need to construct a content object to send this data, here we can use ByteArrayContent but you can use a different type
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var byteContent = new ByteArrayContent(buffer);
Then send the request
var responseMessage = await client.PostAsync(_apiUrl, byteContent);
Figured out the issue. Have to use HttpVersion10 instead of HttpVersion11.

Strange behavior in HttpRequestMessage's Content-Type header

I tried to make HTTP POST request with application/json in body to an external web-service from C# (.NET Core 2.2.104).
I've already read all similar questions in SO and wrote this code:
SignXmlRequestDto requestBody = new SignXmlRequestDto(p12, model.SignCertPin, model.Data);
string json = JsonConvert.SerializeObject(requestBody);
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = ncanNodeUrl,
Headers =
{
{ HttpRequestHeader.ContentType.ToString(), "application/json" }
},
Content = new StringContent(JsonConvert.SerializeObject(json))
};
var response = await httpClient.SendAsync(httpRequestMessage);
string responseString = await response.Content.ReadAsStringAsync();
I am getting an error from service, it says: "Invalid header Content-Type. Please set Content-Type to application/json". What is interesting here, if I simulate this request from Postman, then everything work well and I get successful response.
Updated: as #Kristóf Tóth suggested, I modified my code to:
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = ncanNodeUrl,
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
var response = await httpClient.SendAsync(httpRequestMessage);
string responseString = await response.Content.ReadAsStringAsync();
but it still gives me the same error message.
Content-Type is a content header. It should be set on the content, not the request itself. This can be done either using the StringContent(string,Encoding,string) constructor :
Content = new StringContent(JsonConvert.SerializeObject(json),Encoding.UTF8, "application/json")
or by setting the StringContent's Headers.ContentType property :
var content=new StringContent(JsonConvert.SerializeObject(json));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
This might be an encoding issue. You should use JsonContent not StringContent OR you can do something similar:
// Serialize into JSON String
var stringPayload = JsonConvert.SerializeObject(payload);
// Wrap JSON StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

Can't get body data on server using C# code

I'm trying to send a json content inside the body. But unfortunately, I don't get the data in the server. Same data is received using postman tool.
Here is the code I'm running
private string callAPI(string function, string content)
{
using (var httpClient = new HttpClient())
{
string url = function;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", txt_sessionKey.Text);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
httpClient.BaseAddress = new Uri(baseUrlV2);
var json = new StringContent(content, Encoding.UTF8, "application/json");
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Put,
RequestUri = new Uri(baseUrlV2+function),
Content = json
};
HttpContent contentRes = httpClient.SendAsync(request).Result.Content;
return contentRes.ReadAsStringAsync().Result;
}
}
What am I missing here?

PUT request working in vb.net but not in C#.net

I am developing a REST client in C# that performs the following operation:
It sends a POST request to the server with a query string parameter PolicyId=myhotp and this json data {"uid":"name"}.
The server responds with json data with state id like this {"state":"323434j2hj"}
I extract the value of "state" from the received json data and send
it in another PUT request to the same server with OTP in order to verify. stateid is sent as query string parameter StateId=ihhfueh8f88 and otp is sent as json data {"otp":"123456"}. The server verifies OTP against state id.
But the server responds that the stateid is invalid. Irony is that this same procedure works when I use old way i.e. Microsoft.XMLHTTP to make requests but it doesn't work with HTTP Client. I am not able to transfer state id in query string.
Here is my code using HTTP Client:
User user = new User();
user.uid = "username";
String json = JsonConvert.SerializeObject(user);
MessageBox.Show(json);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://fqdn");
client.DefaultRequestHeaders.Add("Accept", "application/json");
var response = client.PostAsync("api?myhotp", new StringContent(json, Encoding.UTF8, "application/json")).Result;
var contents = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(contents);
var obj = JObject.Parse(contents);
string id = (string)obj["state"];
MessageBox.Show(id);
Otp otpObj = new Otp();
otpObj.otp = "123456";
String jsonotp = JsonConvert.SerializeObject(otpObj);
MessageBox.Show(jsonotp);
client = new HttpClient();
client.BaseAddress = new Uri("http://fqdn");
client.DefaultRequestHeaders.Add("Accept", "application/json");
response = client.PutAsync("api?StateId="+id, new StringContent(json, Encoding.UTF8, "application/json")).Result;
contents = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(contents);
Here is the code with Microsoft.XMLHTTP:
Type xmlType = Type.GetTypeFromProgID("Microsoft.XMLHTTP");
dynamic objXML = Activator.CreateInstance(xmlType);
objXML.Open("POST", "http://fqdn/api?PolicyId=myhotp", false);
objXML.setRequestHeader("Content-Type", "application/json");
objXML.setRequestHeader("Accept", "application/json");
//objXML.setOption(2, 13056);
objXML.Send(json);
MessageBox.Show(objXML.status.ToString());
MessageBox.Show(objXML.responseText.ToString());
var obj = JObject.Parse(objXML.responseText.ToString());
String id = (String)obj["state"];
MessageBox.Show(id);
Otp otpObj = new Otp();
otpObj.otp = "123456";
json = JsonConvert.SerializeObject(otpObj);
MessageBox.Show(json);
objXML.Open("PUT", "http://fqdn/api?StateId="+id, false);
objXML.setRequestHeader("Content-Type", "application/json");
objXML.setRequestHeader("Accept", "application/json");
objXML.Send(json);
MessageBox.Show(objXML.status.ToString());
MessageBox.Show(objXML.responseText.ToString());

Categories