By posting a request to my database, I only get string values .For some reason, the floating values don't get to the DB.
Model
public DateTime ? Date {get;set; }
public double latitud { get; set; }
public double longitud { get; set; }
public string Name { get; set; }
Model Request = Model;
Request.latitud=location.Latitude;
Request.longitud=location.Longitude;
Request.Date=DateTime.Now;
Request.Name=Name;
Service:
public async Task<string> Post(Model Request)
{
var response = new ServiceResponse<string>();
using (var httpClient = new HttpClient())
{
InitClient(httpClient);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation(
"Content-Type", "application/json");
var result = await httpClient.PostAsync(API_URL,
new
StringContent(JsonConvert.SerializeObject(Request),
System.Text.Encoding.UTF8, "application/json"));
Debug.WriteLine("post results : " + result.Content);
}
}
return response;
}
Date, Name is successfully posted anytime I called the service,
However, none of the doubles values does. NOTE- I am 100% sure that all the values are been sent in the object Request.
Related
Hey all so here is the JSON string I expect back {\"status\":\"success\",\"locations\":[{\"id\":\"24\",\"name\":\"Test New Location Test\",\"contact_first_name\":\"Test\",\"contact_last_name\":\"Test\",\"contact_email\":\"test#email.com\",\"contact_phone_number\":\"(555) 555-5555\",\"billing_address\":\"Test\",\"billing_city\":\"Test\",\"billing_state\":\"AK\",\"billing_zip\":\"55555\",\"traps\":[]}]}
I am trying to store all the different parts that make up a location to an object list such as id, name, contact_first_name etc.. I think what is tripping me up is the status in front that is making it a little more difficult for me access the different locations.
I am following this tutorial that seems pretty clear but haven't gotten it to work on my end yet. https://www.youtube.com/watch?v=XssLaKDRV4Y
The below code is part of my Service class and it works in getting the expected http response (mentioned above) and getting the success message. When I uncomment the few lines of code below my app breaks and doesn't store any objects to a list.
public async Task<string> GetLocationData()
{
var user_id = Convert.ToString(App.Current.Properties["user_id"]);
var session = Convert.ToString(App.Current.Properties["session"]);
var key = "randomkeystring";
var body = new List<KeyValuePair<string, string>>();
body.Add(new KeyValuePair<string, string>("user_id", user_id));
body.Add(new KeyValuePair<string, string>("session", session));
body.Add(new KeyValuePair<string, string>("key", key));
try
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, "apiurl/api/something") { Content = new FormUrlEncodedContent(body) };
var result = await client.SendAsync(request);
if (!result.IsSuccessStatusCode)
{
return "false";
}
//string representation
var stringResponseFromServer = await result.Content.ReadAsStringAsync();
//convert JSON to series of objects
//LocationCollection locationCollection = JsonConvert.DeserializeObject<LocationCollection>(stringResponseFromServer);
//System.Diagnostics.Debug.WriteLine(locationCollection.locations.Count);
var response = JsonConvert
.DeserializeObject<GetLocationDataResponse>(stringResponseFromServer);
if (response == null) return "false";
jsonString.HttpGetLocationDataString += stringResponseFromServer;
return stringResponseFromServer;
}
}
catch
{
return "false";
}
}
My locations.cs looks like this
public class Locations
{
public int id { get; set; }
public string name { get; set; }
public string contact_first_name { get; set; }
public string contact_last_name { get; set; }
public string contact_email { get; set; }
public string contact_phone_number { get; set; }
public string billing_address { get; set; }
public string billing_city { get; set; }
public string billing_state { get; set; }
public string billing_zip { get; set; }
public string traps { get; set; }
}
Then I have a LocationCollection.cs where i hope to store the different locations so I can loop through them later and do whatever I need to do to them.
public class LocationCollection
{
public List<Locations> locations { get; set; }
}
And then I call the method on my MainPage after the user logs in
insectService.GetLocationData().ContinueWith(async (task) =>
{
var getLocationDataResponse = JsonConvert.DeserializeObject<GetLocationDataResponse>(task.Result);
if (getLocationDataResponse.status == "failure")
{
await DisplayAlert("Location Data Failure", "Could not retrieve data", "Try Again");
await Navigation.PushModalAsync(new LoginPage(), true);
}
//System.Diagnostics.Debug.WriteLine(getLocationDataResponse.locations.ToString());
if (getLocationDataResponse.status == "success")
{
await DisplayAlert("Location Data Success", "Successfully Recovered Data", "Back to Main Page");
}
}); //TaskScheduler.FromCurrentSynchronizationContext());
Right now I am able to get the expect JSON string of {\"status\":\"success\",\"locations\":[{\"id\":\"24\",\"name\":\"Test New Location Test\",\"contact_first_name\":\"Test\",\"contact_last_name\":\"Test\",\"contact_email\":\"test#email.com\",\"contact_phone_number\":\"(555) 555-5555\",\"billing_address\":\"Test\",\"billing_city\":\"Test\",\"billing_state\":\"AK\",\"billing_zip\":\"55555\",\"traps\":[]}]} and am able to check if the status is success or failure. However I am having trouble storing the different parts of "locations" into a list. Any suggestions?
You can give a try deserilizing your api result in to a result model, then from there again de serialize to location model. Example:
My API Model
public class ApiResult
{
public Int32 Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
}
Inside Data I copy all my return result from API, then Deserialize to exact Model. Here is the example:
public static List<Models.OrderList> RetrieveOrderList(string host, List<Models.FilterCondition> filter)
{
string sResult = HttpHelper.httpPost(host + "api/Order/RetrieveOrderList", Newtonsoft.Json.JsonConvert.SerializeObject(filter));
Models.ApiResult mResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.ApiResult>(sResult);
if (mResult.Status == 0)
throw new Exception(mResult.Message);
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Models.OrderList>>(mResult.Data);
}
If you see the above My return result(string), I deserialize to API result Model, then again finally deserialize to OrderList Model. Hope this help to sort out your issue.
Update: API Controller
I forgot to mention one more point. On the API Controller Side Your result need to copied to API Model.
Here is the Example
[HttpPost]
public Models.ApiResult RetrieveOrderList(List<Models.FilterCondition> conditions)
{
Models.ApiResult mResult = new Models.ApiResult();
try
{
List<Models.OrderList>mOrderList= BLL.Order.RetrieveOrderList(conditions);
mResult.Status = 1;
mResult.Message = "Success";
mResult.Data = Newtonsoft.Json.JsonConvert.SerializeObject(mOrderList);
return mResult;
}
catch (Exception ex)
{
mResult.Status = 0;
mResult.Message = ex.Message;
mResult.Data = "";
return mResult;
}
}
My locations model didn't match the JSON response. Once I read what the exception was in my catch statement I saw that 'traps' was supposed to be another list. After I changed traps property to a List and then made another class for 'traps' everything worked fine.
I have an azure function below, I have webhook trigger when i mention my bot in my chat. It triggers the azure Function but it sends infinite messages back to my room and I have to stop the entire function.
#r "Newtonsoft.Json"
using System.Net; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Primitives; using Newtonsoft.Json;
public static async Task<object> Run(HttpRequestMessage req, TraceWriter log) {
string jsonContent = await req.Content.ReadAsStringAsync();
var dto = JsonConvert.DeserializeObject<RootObject>(jsonContent);
string callerName = dto.data.personEmail;
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://****************"))
{
request.Headers.TryAddWithoutValidation("Cache-Control", "no-cache");
request.Headers.TryAddWithoutValidation("Authorization", "Bearer *****************************************************");
request.Headers.TryAddWithoutValidation("Postman-Token", "**********************");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent(callerName), "markdown");
multipartContent.Add(new StringContent("***********************************"), "roomId");
request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
}
}
return req.CreateResponse(HttpStatusCode.OK);
}
public class Data {
public string id { get; set; }
public string roomId { get; set; }
public string roomType { get; set; }
public string personId { get; set; }
public string personEmail { get; set; }
public List<string> mentionedPeople { get; set; }
public DateTime created { get; set; }
}
public class RootObject {
public Data data { get; set; }
}
You need to bind it as an HttpTrigger. Currently, your function is just running without any type of triggering.
There are many types.
HttpTrigger
TimerTrigger
BlobTrigger
QueueTrigger
EventHubTrigger
SendGridTrigger
Many others, mentioned below in Microsoft example URL
Package for HttpTrigger: https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.Http
You may also need:
https://www.nuget.org/packages/Microsoft.Azure.WebJobs
Example(from https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook):
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req,
TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// parse query parameter
string name = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
// Set name to query string or body data
name = name ?? data?.name;
return name == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}
I have been searching solution for few hours and I can't find answer to my problem.
I want to send a post method to a web api and I've tried it first on postman using these json content and it is working.
{
"ETickets": [
{
"TicketName": "Weekend - Regular Day Pass",
"TicketAccessType": "PA",
"TicketGuest": "RDP",
"IsWeekday": true
},
{
"TicketName": "Weekend - Regular Day Pass",
"TicketAccessType": "PA",
"TicketGuest": "RDP",
"IsWeekday": true
}
],
"TransactDetails": {
"CompanyCode": "ONLINE",
"Surname": "Dela Cruz",
"FirstName": "Juan",
"BookingReference": "1113",
"BookingDate": "2018-08-16T11:31:20:04"
}
}
However, when I try it in coding style, I can't make it to work. It says 500 internal server error upon debugging.
Here's the error screenshot:
Here's my few codes related to my issue:
TransactionDetailsViewModel finale = new TransactionDetailsViewModel();
finale.TransacDetails = transacDetail;
finale.ETickets = lsTickets.ToArray();
client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", System.Web.HttpContext.Current.Session["WebApiAccessToken"].ToString());
HttpResponseMessage responseMessage = await client.PostAsJsonAsync(url + "api/Transaction/SendTransaction/", finale);
And here's the model I'ved used:
public class TransactionDetailsViewModel
{
public TransactionDetails TransacDetails { get; set; }
public TicketDetailsModel[] ETickets { get; set; }
}
public class TransactionDetails
{
public string CompanyCode { get; set; }
public string Surname { get; set; }
public string FirstName { get; set; }
public string BookingReference { get; set; }
public DateTime? BookingDate { get; set; }
}
public class TicketDetailsModel
{
public string TicketAccessType { get; set; }
public string TicketGuest { get; set; }
public string TicketName { get; set; }
public bool IsWeekday { get; set; }
}
Do I send the data with the correct format or something to adjust to make it work on sending to a PostAsJsonAsync?
Any help will be much appreciated. Thanks.
Please, modify your code just like as
var data = new StringContent(JsonConvert.SerializeObject(finale, Encoding.UTF8, "application/json"));
HttpResponseMessage responseMessage = await client.PostAsJsonAsync("api/Transaction/SendTransaction/", data);
OR You can make request and then send like as
HttpResponseMessage response = null;
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Post, url+"/api/Transaction/SendTransaction"))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", System.Web.HttpContext.Current.Session["WebApiAccessToken"].ToString());
var data = new StringContent(JsonConvert.SerializeObject(finale, Encoding.UTF8, "application/json"));
request.Content = data;
response = await client.SendAsync(request);
}
}
Please try below line to post data
httpClient.PostAsync(url + "/api /Transaction/SendTransaction/", new StringContent(JsonConvert.SerializeObject(finale).ToString(), Encoding.UTF8, "application/json")).Result;
I tried many time today to call a web api function with POST (HttpClient.PostAsync) method . But unfortunately I can't.
Only the call with GET (HttpClient.GetAsync) method working with success.
I try to follow many sample on the net, but always the same error. ("Not Found")
Thank you so much if somebody can help me
Here is the C# Web API:
[RoutePrefix("NewAreaMap")]
public class NewAreaMapController: ApiController
{
[HttpPost]
[ActionName("PostCreateAreaTemp")]
public AreaTemp PostCreateAreaTemp(double southLatitude, double westLongitude, double northLatitude, double eastLongitude, int countryId, int worldId)
{
AreaTemp newTempMap = new AreaTemp();
//.....
* * Here is the C# code from client side: * *
using(var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["SrvWebApiPath"].ToString());
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var values = new Dictionary < string,
string > ()
{
{
"southLatitude", southLatitude.ToString()
},
{
"westLongitude", westLongitude.ToString()
},
{
"northLatitude", northLatitude.ToString()
},
{
"eastLongitude", eastLongitude.ToString()
},
{
"countryId", countryId.ToString()
},
{
"worldId", worldId.ToString()
}
};
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("api/NewAreaMap/PostCreateAreaTemp", content)
if (response.IsSuccessStatusCode)
{
string jsonData = response.Content.ReadAsStringAsync().Result;
newAreTemp = JsonConvert.DeserializeObject < AreaTemp > (jsonData);
}
}
The GET call work well with the following Url :
HttpResponseMessage response = await client.GetAsync("api/NewAreaMap/GetAreaTemp/?latitudeAreaCenter=7.02&longitudeAreaCenter=9.05");
Since you're posting a JSON, you might as well send it as an object. Or if you still want to keep the dictionary and the signature for the method you could try:
var content = new StringContent(JsonConvert.SerializeObject(values),
Encoding.UTF8, "application/json");
Instead of
var content = new FormUrlEncodedContent(values);
Here's an example with an object.
public class SampleObject
{
public double SouthLatitude { get; set; }
public double WestLongitude { get; set; }
public double NorthLatitude { get; set; }
public double EastLongitude { get; set; }
public int CountryId { get; set; }
public int WorldId { get; set; }
}
And change your request.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["SrvWebApiPath"].ToString());
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var obj = new SampleObject
{
SouthLatitude = southLatitude,
WestLongitude = westLongitude,
NorthLatitude = northLatitude,
EastLongitude = eastLongitude,
CountryId = countryId,
WorldId = worldId
};
// Send it as StringContent.
var request = new StringContent(JsonConvert.SerializeObject(obj),
Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("api/NewAreaMap/PostCreateAreaTemp", request)
if (response.IsSuccessStatusCode)
{
string jsonData = response.Content.ReadAsStringAsync().Result;
newAreTemp = JsonConvert.DeserializeObject<AreaTemp>(jsonData);
}
}
And the signature on the server.
public AreaTemp PostCreateAreaTemp(SampleObject sampleObject)
Or if needed:
public AreaTemp PostCreateAreaTemp([FromBody]SampleObject sampleObject)
replace your method parameter with object because you are passing full object
"content" from the httpclient so in that case you need to use same object here also with [frombody] attribute
methodname([FromBody] Content content)
define all the properties in one class and use . Hope it will helpful for you.
Please try to use FromBody attribute with your action parameter.
I am using WPF as Client and Web api as Service. For add new event click button and update button in WPF not returning to http post action in api controller and also returning error Internal server error.
Http Post method
[HttpPost]
public HttpResponseMessage PostEvent(EventFormModel event1)
{
if (ModelState.IsValid)
{
var command = new CreateOrUpdateEventCommand(event1.EventId, event1.EventAgenda, event1.Description, event1.EventDate, event1.Location, event1.UserId);
var result = commandBus.Submit(command);
if (result.Success)
{
var response = Request.CreateResponse(HttpStatusCode.Created, event1);
string uri = Url.Link("DefaultApi", new { id = event1.EventId });
response.Headers.Location = new Uri(uri);
return response;
}
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
WPF click event:
private async void btnNewEvent_Click(object sender, RoutedEventArgs e)
{
var event1 = new Event()
{
EventAgenda = txtAgenda.Text,
Description = txtEventDescription.Text,
Location=txtLocation.Text,
UserId=Convert.ToInt32(txtUserId.Text),
EventId=Convert.ToInt32(txtEventId.Text),
EventDate=Convert.ToDateTime(dateEventDate.Text),
};
client.BaseAddress = new Uri("http://localhost:40926/api/Event");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync("api/Event", event1).Result;
if (response.IsSuccessStatusCode)
{
MessageBox.Show("added" + response);
txtAgenda.Text = "";
txtEventDescription.Text = "";
txtLocation.Text = "";
txtUserId.Text = "";
txtEventId.Text = "";
dateEventDate.Text = "";
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
Event class in WPF application:
public class Event
{
public int EventId { get; set; }
public int UserId { get; set; }
// [Required(ErrorMessage = "Agenda Required")]
//[Display(Name = "Movie Name")]
public string EventAgenda { get; set; }
// [Required(ErrorMessage = "Location Required")]
public string Location { get; set; }
// [Required(ErrorMessage = "Date Required")]
public DateTime EventDate { get; set; }
public string Description { get; set; }
// public string ReminderType { get; set; }
}
I used breakpoints near post action and also click event. but in click event near
var response = client.PostAsJsonAsync("api/Event", event1).Result; not returing to api post method and returning Response status code does not indicate success: 500 (Internal Server Error). Similar issue for Update also
-Thanks Sindhu
You included some parts of the URI twice.
client.BaseAddress = new Uri("http://localhost:40926/api/Event");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync("api/Event", event1).Result;
You duplicated "api/Event". And would get the URI, api/Event/api/Event/. For your BaseAddress you only need hostname and port.
e.g.
client.BaseAddress = new Uri("http://localhost:40926");
var response = client.PostAsJsonAsync("api/Event", event1).Result;
Also you are getting a 500 Internal Server error from somewhere else in your sever code. I can't where right now.