PostAsJsonAsyncResponse is not returning the result - c#

I'm having issues retrieving the response with the populated result within the Dispatch method, I'm not sure what I'm missing :(
The issue seems to be when it's deserializing as the responseBody is correct until that point.
Can anyone help?
public async Task<Response> Dispatch(DispatchItem dispatchRequest)
{
var url = string.Format("dispatch/dispatchitem.json");
var response = PostAsJsonAsyncResponse<DispatchItem , DispatchResponse>(url, dispatchRequest);
response.Wait();
return new Response();
}
protected async Task<Response<TResponse>> PostAsJsonAsyncResponse<TModel, TResponse>(string url, TModel model)
{
using (var client = new HttpClient())
{
var authCredential = Encoding.UTF8.GetBytes($"{Username}:{Password}");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authCredential));
client.BaseAddress = new Uri(APIUrl);
var response = client.PostAsJsonAsync(url, model);
response.Wait();
var responseBody = await response.Result.Content.ReadAsStringAsync();
if (!response.Result.IsSuccessStatusCode)
throw new ApiException(response.Result.StatusCode, responseBody);
return JsonConvert.DeserializeObject<Response<TResponse>>(responseBody);
}
}
public class Response : Response<string>
{
}
public class Response<T>
{
public T Result { get; set; }
public bool IsSuccessful { get; set; }
}
}
public class DispatchResponse
{
public int Id { get; set; }
public guid Reference { get; set; }
}

Related

Cannot deserialize the current JSON object into type 'System.Collections.Generic.List1' in Xamarin Forms

I'm having an error in Xamarin Forms I tried to deserialize the object does anyone know What did I do wrong here?
This is my method
private async void GetEmployee()
{
var _token = await GetAccessToken();
//List<D365Employee> Employee = null;
using (var _clientD365 = new HttpClient())
{
var _uri = "domain here";
_client.BaseAddress = new Uri(_uri);
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);
var _response = await _clientD365.GetAsync("my endpoint here");
var Emp = JsonConvert.DeserializeObject<List<Employee>>(_response.Content.ReadAsStringAsync().Result);
Employee = new ObservableCollection<Employee>(Emp);
}
}
This is my Model
public class Employee
{
[JsonProperty("#odata.etag")]
public string Context { get; set; }
public IList<EmployeeDetails> Value { get; set; }
}
public class EmployeeDetails
{
public string PersonnelNumber { get; set; }
public string EmploymentLegalEntityId { get; set; }
public string DimensionDisplayValue { get; set; }
}
This is the JSON I try to parse
{
"#odata.context": "https://employee.dynamics.com/data/$metadata#Employees(PersonnelNumber,EmploymentLegalEntityId,DimensionDisplayValue)",
"value": [
{
"#odata.etag": "W/\"JzEsNTYzNzE0NDYwMzsxNDg2NTk2NzY0LDU2MzcxNDc2OTM7MSw1NjM3MTQ0NjAzOzEsNTYzNzE0NDYwMzsxLDU2MzcxNDczNzE7MCwwOzAsMDsyNTY0OTEwODksNTYzwJw==\"",
"PersonnelNumber": "ID111028",
"EmploymentLegalEntityId": "OOP",
"DimensionDisplayValue": "----",
}
]
}
That JSON is a single object, not a list, so you need to deserialize it as a single object.
var Emp = JsonConvert.DeserializeObject<Employee>(await _response.Content.ReadAsStringAsync());

Xamarin.Forms Consume API

Can someone help me?
I'm try to consume api in my apps (I'm still learning). I can successfully call the api and get the data, but debug ended in DeserializeObject.
Can someone help me, and tell what must I do? or reference how to fix this?
This is my code:
My ViewModels
from ViewModels I call GetHeroes(), which calls my class in services.
public class DotaViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public DotaViewModel()
{
GetHeroes(); // Start From Here
}
IDotaApi _rest = DependencyService.Get<IDotaApi>();
private ObservableCollection<Hero> heroes;
public ObservableCollection<Hero> Heroes
{
get { return heroes; }
set
{
heroes = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Heroes"));
}
}
public async void GetHeroes()
{
var result = await _rest.getheroes(); // Go Inside Here
if (result != null)
{
}
}
}
My Services
I got the data and stored it to var result, but my debug just when I DeserializeObject.
public class DotaApi : IDotaApi
{
string Base_url = "https://api.opendota.com/api/heroes";
public async Task<ObservableCollection<Hero>> getheroes()
{
string url = Base_url;
HttpClient client = new HttpClient();
HttpResponseMessage responseMessage = await client.GetAsync(url);
if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
{
var result = await responseMessage.Content.ReadAsStringAsync(); // I Got Data Here
var json = JsonConvert.DeserializeObject<ObservableCollection<Hero>>(result); // But Stuck Here
return json;
}
return null;
}
}
This is My Model
public class Hero
{
public int id { get; set; }
public string name { get; set; }
public string localized_name { get; set; }
public string primary_attr { get; set; }
public string attack_type { get; set; }
public List<string> roles { get; set; }
public int legs { get; set; }
//[
//{"id":1,
//"name":"npc_dota_hero_antimage",
//"localized_name":"Anti-Mage",
//"primary_attr":"agi",
//"attack_type":"Melee",
//"roles":["Carry","Escape","Nuker"],
//"legs":2}
//}
//]
}
Try to implement the API calling method like below and add a debug point to the exception and check the issue
public async Task<ObservableCollection<Hero>> getheroes()
{
string Base_url = "https://api.opendota.com/api/heroes";
using (var httpClient = new HttpClient())
{
var data = new ObservableCollection<Hero>();
try
{
var content = new StringContent(requestBody, Encoding.UTF8, "application/json");
var result = await httpClient.GetAsync(Base_url);
var response = await result.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<ObservableCollection<Hero>>(response);
if (result.IsSuccessStatusCode && result.StatusCode == HttpStatusCode.OK)
{
return data;
}
return null;
}
catch (Exception exp)
{
return null;
}
}
}
Thanks For all,
I finally solved the problem,
this is purely my fault cause I didn't really understand how it worked before,
so i try to understand more deeply about ObservableCollection and how to debug
now i know, there is nothing wrong with DeserializeObject like i said in my question (sorry for that), the problem is in GetHeroes() function
public async void GetHeroes()
{
var result = await _rest.getheroes();
if (result != null)
{
Heroes = result; // i missed this code, so. I haven't entered my data before
}
}

C# HttpClient post content with FormUrlEncodedContent object in Dictionary string/object

I am trying to post a contect to my server.
This is how I have been doing it for the past and it was working until I had to use objects besides strings.
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(authType, tokens);
var postParams = new Dictionary<string, object>();
postParams.Add("string", string);
postParams.Add("int", string);
postParams.Add("datetime", DateTime);
postParams.Add("datetime", DateTime);
postParams.Add("Match", Match);
postParams.Add("TicketId", token);
using (var postContent = new FormUrlEncodedContent(postParams.ToDictionary()))
{
var myContent = JsonConvert.SerializeObject(postParams);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using (HttpResponseMessage response = await client.PostAsync(#"http://url/api", byteContent))
{
response.EnsureSuccessStatusCode(); // Throw if httpcode is an error
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
var Json = JsonConvert.DeserializeObject<bool>(result);
return Json;
}
}
}
}
And this is how my request is supposed to be.
methode: POST
object: {
"title":"test-ticket-2",
"detail": "Description test create ticket in prod",
"dateStart": "2019-10-06",
"dateEnd": "2019-10-12",
"ratio": "2.15",
"matchResult": "2",
"matchs": [
{
"Teams": "Test-match-1",
"Proposal": "3x",
"DateStart": "2019-10-06 18:00",
"DateEnd": "2019-10-06 20:00",
"Payout": "0.6"
}
]
I have no idea IF and HOW I can add Objects other than string and make the request.
Any ideas?
Edit: Match looks like this
public class Match
{
public int Id { get; set; }
public string Teams { get; set; }
public string MatchResults { get; set; }
public string Proposal { get; set; }
public string Payout { get; set; }
public DateTime? DateStart { get; set; }
public DateTime? DateEnd { get; set; }
public Uri Ball { get; set; }
public int TicketId { get; set; }
}
HOW I can add Objects other than string and make the request. Any
ideas?
using (HttpClient httpclient = new HttpClient())
{
Models.ApplicationUser applicationUser = new ApplicationUser();
string serialized = Newtonsoft.Json.JsonConvert.SerializeObject(applicationUser);
StringContent stringContent = new StringContent(serialized);
httpclient.PostAsync("url", stringContent);
}
Hope you want to do something like this

ASP.Net Web APi C# - GetAsync not returning XML response content

I am calling an external service using GetAsync() and passing parameters in query string. When i check the content in the response, i don't see anything returned, however it returns 200 OK and in fiddler it returns me the XML response correctly. I need the XML response to get de-serialize to an C# object and then further save it to DB.
Things tried:
1) Tried this by adding this setting in global- app_start(), It didn't help
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
2) Created an object and tried to sent it via GetAysnc, that didn't help either.
public class Request
{
[XmlElement]
public string XML { get; set; }
[XmlElement]
public List<string> ProNumber { get; set; }
}
2) Should i try passing parameters in query string and expect json result? if i add mediatyperformatter to application/json?
Here is my code:
public async Task<HttpResponseMessage> GetData()
{
string requestString = "&xml=Y&PRONumber=82040X,03117X";
string result = "";
string url = #"http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController";
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
HttpResponseMessage response = await client.GetAsync(url+requestString);
if (response.IsSuccessStatusCode)
{
return response;
}
}
}
catch (Exception ex)
{
result = ex.Message;
}
return null;
}
EDIT:
Shipments scp = null;
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Shipment";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(Shipment), xRoot);
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
{
scp = (Shipments)serializer.Deserialize(stream);
}
Model:
public class Shipments
{
[XmlArrayItem(Type = typeof(Shipment))]
public Shipment[] Shipment;
}
public class Shipment
{
[XmlAttribute()]
public int returnCode { get; set; }
.................
..............
Getting error:<SHIPMENTS xmlns=''> was not expected.
Any help on this is much appreciated.
Thanks,
WH
This worked for me -
var client = new HttpClient();
var data = client.GetStringAsync("http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController&xml=Y&PRONumber=82040X,03117X").Result;
var ser = new XmlSerializer(typeof(Shipments));
var t = (Shipments)ser.Deserialize(new StringReader(data));
public class Shipment
{
public string returnCode { get; set; }
public string returnMessage { get; set; }
public string freightBillNumber { get; set; }
//props
}
[XmlRoot(ElementName = "SHIPMENTS")]
public class Shipments
{
[XmlElement(ElementName = "SHIPMENT")]
public List<Shipment> SHIPMENT { get; set; }
}
EDIT
this works as well -
var data = client.GetStreamAsync("http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController&xml=Y&PRONumber=82040X,03117X").Result;
EDIT
works as well -
var client = new HttpClient();
var data = client.GetAsync("http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController&xml=Y&PRONumber=82040X,03117X").Result;
var ser = new XmlSerializer(typeof(Shipments));
var t = (Shipments)ser.Deserialize(data.Content.ReadAsStreamAsync().Result);

Part of object that is returned is null

I have the following method in my web api controller
public HttpResponseMessage PostGrantAccess(DeviceAccessRequest deviceAccessRequest)
{
var deviceId = deviceAccessRequest.DeviceId;
var deviceAccessResponse = new DeviceAccessResponse(deviceAccessRequest.RequestId)
{
Status = "OK"
};
var response = Request.CreateResponse<DeviceAccessResponse>(HttpStatusCode.OK, deviceAccessResponse);
return response;
}
This is the calling client code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:55208/");
var request = new DeviceAccessRequest
{
RequestId = Guid.NewGuid().ToString(),
DeviceId = "bla",
LoginId = "tester",
Password = "haha" ,
};
var response = client.PostAsJsonAsync("api/accesspanel", request).Result;
if (response.IsSuccessStatusCode)
{
var deviceAccessResponse = response.Content.ReadAsAsync<DeviceAccessResponse>().Result;
}
}
Object classes:
public class DeviceAccessResponse : ResponseBase
{
public DeviceAccessResponse()
{
}
public DeviceAccessResponse(string correlationId)
: base(correlationId)
{
}
public string Status { get; set; }
}
public class ResponseBase
{
private string correlationId;
public ResponseBase()
{
}
public ResponseBase(string correlationId)
{
this.correlationId = correlationId;
}
}
I am able to receive DeviceAccessRequest in my controller just fine, I am able to get the guid string.
However, after returning the response back to the client, I am only able to get back Status = "OK", the correlationId is null instead of containing the guid string which I have assigned in the client code with this line
var deviceAccessResponse = new DeviceAccessResponse(deviceAccessRequest.RequestId)
What did I miss?
is the response.Content.ReadAsAsync<DeviceAccessResponse>().Result; the correct code to use to reconstruct my whole object?
Your correlationId is a private field. If you want it to serialize over the wire, you probably need to make a public property to expose it.
You should make the correlationId a public property if you want it to be exposed and travel to the client:
public class ResponseBase
{
public ResponseBase()
{
}
public string CorrelationId { get; set; }
public ResponseBase(string correlationId)
{
this.CorrelationId = correlationId;
}
}

Categories