I'm POSTing to API that is returning a 409 response code along with a response body that looks like this:
{
"message": "Exception thrown.",
"errorDescription": "Object does not exist"
}
How can I pull out the Response Body and deserialize it?
I am using HttpClient:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:60129");
var model = new Inspection
{
CategoryId = 1,
InspectionId = 0,
Descriptor1 = "test descriptor 121212",
Name = "my inspection 1121212"
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(model);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var result = client.PostAsync("api/Inspections/UpdateInspection", stringContent);
var r = result.Result;
I seems like such a common thing to do, but I'm struggling to find where the data is in my result.
You can use ReadAsAsync<T> on the content of the response to a concrete type or ReadAsStringAsync to get the raw JSON string.
Would also suggest using Json.Net for working with the JSON.
var response = await client.PostAsync("api/Inspections/UpdateInspection", stringContent);
var json = await response.Content.ReadAsStringAsync();
A concrete response model can be created
public class ErrorBody {
public string message { get; set; }
public string errorDescription { get; set; }
}
and used to read responses that are not successful.
var response = await client.PostAsync("api/Inspections/UpdateInspection", stringContent);
if(response.IsSuccessStatusCode) {
//...
} else {
var error = await response.Content.ReadAsAsync<ErrorBody>();
//...do something with error.
}
Related
Trying to update my JSON file, I get the return code 'OK' (200), but the file doesn't change. The JSON string contains the updated entry.
What do I wrong?
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
RootObject root = null;
HttpResponseMessage HttpResponseMessage = await httpClient.GetAsync("http://localhost/fruits.json",
HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
if (HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
{
HttpContent HttpContent = HttpResponseMessage.Content;
string MyContent = await HttpContent.ReadAsStringAsync();
root = JsonConvert.DeserializeObject<RootObject>(MyContent);
ReturnContentModels = new AsyncObservableCollection<ContentModel>(root.products);
Debugger.Break();
}
ContentModel contentModel = ReturnContentModels[0];
contentModel.Name = "Apfelsinen";
List<ContentModel> products1 = new List<ContentModel>(ReturnContentModels);
RootObject root1 = new RootObject
{
meta = root.meta,
products = products1
};
string json = JsonConvert.SerializeObject(root1, Formatting.Indented);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://localhost/fruits.json", stringContent);
Debugger.Break();
What I understand is that you are currently getting the record from a JSON file directly and modifying it. You cannot directly modify a file using httpClient. You need a server (back-end application) of some kind to understand your POST request.
You can use JSON-Server to serve your JSONfile and make GET, POST and other requests to it.
I'm trying to send a http post request in JSON format which should look like this:
{
"id":"72832",
"name":"John"
}
I have attempted to do it like below but if I am correct this is not sending a request in json format.
var values = new Dictionary<string,string>
{
{"id","72832"},
{"name","John"}
};
using (HttpClient client = new HttpClient())
{
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("https://myurl",content);
// code to do something with response
}
How could I modify the code to send the request in json format?
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;
}
I would start off by using RestSharp.
dotnet add package RestSharp
Then you can send requests like this:
public async Task<IRestResult> PostAsync(string url, object body)
{
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.Post);
request.AddJsonBody(body);
var response = await client.ExecuteAsync(request);
return response;
}
Just pass in your dictionary as the body object - I would recommend creating a DTOS class to send through though.
Then you can get certain aspects of the RestResponse object that is returned like:
var returnContent = response.Content;
var statusCode = response.StatusCode;
So I've looked around for an answer for this but nothing I've found even comes close to solving it.
I'm trying to set up a Post method on my Web API but no matter what I do it just gives me an internal server error.
I've tried adding [FromBody] (it's a simple type).
HttpClient client {get;set;}
public APICall()
{
client = new HttpClient
{
BaseAddress = new Uri("http://localhost:1472/api/")
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
}
public void PostTimeTaken(long timeTaken)
{
var response = client.PostAsJsonAsync("Logging", timeTaken).Result;
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.ReasonPhrase);
}
}
and then my controller action looks like this:
public void Post([FromBody] long timeTaken)
{
_api.DataBuilder.NumberOfAPICalls += 1;
_api.DataBuilder.ResponseTimes.Add(timeTaken);
}
I get no error message that could actually explain what's going on, just "Internal server error"
------SOLVED-------
Just in case anyone stumbles across this looking for the same answer, the issue was I was sending the data to the server in an incorrect format, it needed to be ProtoBuf serialised first, code snippet for anyone it might help:
public void PostToAPI(int ThingToSend)
{
using (var stream = new MemoryStream())
{
// serialize to stream
Serializer.Serialize(stream, ThingToSend);
stream.Seek(0, SeekOrigin.Begin);
// send data via HTTP
StreamContent streamContent = new StreamContent(stream);
streamContent.Headers.Add("Content-Type", "application/x-protobuf");
var response = client.PostAsync("Logging", streamContent);
Console.WriteLine(response.Result.IsSuccessStatusCode);
}
}
using (var client = new HttpClient())
{
string url = "http://localhost:7936";
client.BaseAddress = new Uri(url);
var jsonString = JsonConvert.SerializeObject(contentValue);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var result = await client.PostAsync("/Api/Logger/PostActionLog", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
Have you tried to convert
long timeTaken to A model like;
public class TimeModel {
public long TimeTaken {get;set;}
}
public void Post([FromBody] TimeModel time){
// Do Stuff
}
Here the code of creating a simple server
baseUrl = "http://localhost:1472/"; // change based on your domain setting
using (WebApp.Start<StartUp>(url: baseUrl))
{
HttpClient client = new HttpClient();
var resp = client.GetAsync(baseUrl).Result;
}
Here some changes in your code
var requestData = new List<KeyValuePair<string, string>> // here
{
new KeyValuePair<string, string>( "Logging",timeTaken),
};
Console.WriteLine("request data : " + requestData);
FormUrlEncodedContent requestBody = newFormUrlEncodedContent(requestData);
var request = await client.PostAsync("here pass another server API", requestBody);
var response = await request.Content.ReadAsStringAsync();
Console.WriteLine("link response : " + response);
Pls add your controller
[HttpPost] // OWIN - Open Web Interface for .NET
public HttpResponseMessage Post([FromBody] long timeTaken)
{
_api.DataBuilder.NumberOfAPICalls += 1;
_api.DataBuilder.ResponseTimes.Add(timeTaken);
return Request.CreateResponse(HttpStatusCode.OK); //Using Post Method
}
I have an endpoint in my ASP.NET Core 2.1 Controller
[HttpPost]
public async Task<bool> CheckStatus([FromBody] StatusModel model)
{
...code ommited
return true;
}
And I call this endpoint from other place in code like this:
await client.PostAsync('/CheckStatus', payloayd)
How can I retrive a bool value from this request?
Using Newtonsoft.Json, you can read the response of the request and parse it into a bool.
using Newtonsoft.Json;
public async Task<bool> GetBooleanAsync()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = new { };
var url = "my site url";
var payload = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
var req = await client.PostAsync(url, payload);
var response = await req.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<bool>(response);
}
}
UPDATE
Looking back on this from a few years on, this can be simplified without the use of Newtonsoft.Json to read the response, by simply parsing the string data to a boolean.
public async Task<bool> GetBooleanAsync()
{
var data = new { };
var url = "my site url";
var payload = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
using var client = new HttpClient();
var response = await client.PostAsync(url, payload);
var data = await response.Content.ReadAsStringAsync();
return boolean.Parse(data);
}
However, if your boolean value is returned in a JSON object, then Newtonsoft.Json could be used to read that value.
i have the following API json request
"myjsonrequest": {
"ServiceKey": "Hello",
"Identityvals": {
"IDName": "regnum",
"IDValue": "112233"
}
}
any simple way to get the response , im using ASP.net c#
i tried this code
HttpClient client = new HttpClient();
string x = "{'IDName','regnum'},{'IDValue','112233'}";
var Keys = new Dictionary<string, string>
{
{ "ServiceKey", "hello" },
{ "PractitionerIdentity",x}
};
var content = new FormUrlEncodedContent(Keys);
var response = await client.PostAsync("https://apiurl", content);
var responseval = await response.Content.ReadAsStringAsync();
Try this :
var json = new {
ServiceKey = "",
PractitionerIdentity = new {
IDName = "" ,
IDValue = ""
}
};
HttpClient client = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json")
var response = await client.PostAsync("https://apiurl", content);
Your Json data should be saved to a model in the following way:
public class YourJsonData{
public string ServiceKey {get; set;}
//add other names
}
The best thing about this is that if you call your object, you get a variable back for easy usage.
then you can add it in a task:
public async Task<List<YourJsonData>> GetJsonAsync(CancellationToken cancellationToken = default)
{
using (var client = new HttpClient())
{
//Make the request, and ensure we can reach it
var response = await client.GetAsync(yourJosnUrl, cancellationToken);
if (response.IsSuccessStatusCode)
{
//Read the actual stream (download the content)
var content = await response.Content.ReadAsStringAsync();
//Make sure we do have some valid content before we try to deserialize it
if (string.IsNullOrEmpty(content))
{
return new List<YourJsonData>();
}
//Deserialize into a list of yourjsondata
return JsonConvert.DeserializeObject<List<YourJsonData>>(content);
}
}
return new List<YourJsonData>();
}
also if you are lazy, you can replace YourJsonData with dynamic. the downpart here is that you won't be able to see what you are revering to.