ASP.NET Api Client - c#

I'm learning how to create WEB-API client
I've created some simple API:
[HttpGet]
public IHttpActionResult GetInfo()
{
return Ok("Its working!");
}
[HttpPost]
public IHttpActionResult PostInfo(ClientDataDto dto)
{
try
{
someMethod(dto.IdKlienta, dto.Haslo, dto.IdZgloszenia, dto.HardwareInfo, dto.SoftwareInfo);
return Ok("sent");
}
catch
{
return BadRequest();
}
}
For now I just trying to call GET method.
When I use Fiddler with addr
localhost:someport/api/Client2
its working
but when i try to do it by client, which code is below:
private static HttpClient client = new HttpClient();
static void Main(string[] args)
{
#region TESTONLY
var debug = new XMLData();
string HardwareInfoXML = debug.HardwareXML;
string SoftInfoXML = debug.SoftwareXML;
int id_zgloszenia = 20;
int idKlienta = 25;
//haslo = "202cb962ac59075b964b07152d234b70";
#endregion
var data = new ClientDataDto() { HardwareInfo = HardwareInfoXML, SoftwareInfo = SoftInfoXML, IdKlienta = idKlienta, IdZgloszenia = id_zgloszenia };
RunAsync(data);
}
private static async Task RunAsync(ClientDataDto data)
{
var stringContent = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(#"http://localhost:7774/api/client2/");
var url = new Uri(#"http://localhost:7774/api/client2/");
var res1 = await client.GetAsync(url);
var res = await client.PostAsync(url, stringContent);
res.EnsureSuccessStatusCode();
}
Application closing without any info at
var res1 = await client.GetAsync(url);
I have checked to see all exceptions in Debug exception Windows, but it is just closing after trying call GetAsync
PostASync doesn't work too.
What is wrong here?

i'm really sorry that i've posted simpe problem.
sulotion is to add .Wait() on RunAsync(data);
RunAsync(data).Wait();

Related

HttpClient.PostAsJsonAsync crushed without exception

I am trying to call an api(POST method) with HttpClient.PostAsJsonAsync. However, it stopped at httpClient.PostAsJsonAsync without any exception.
The source code as below:
public static async Task<oResult> PostApi(string JSON_sObject, string sEnd_Url) {
oResult oResult = new oResult();
var Data = JsonConvert.DeserializeObject(JSON_sObject);
var Url = "http://localhost:44340/" + sEnd_Url;
HttpClient httpClient = new HttpClient();
try {
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data); // it stopped here
if (response.IsSuccessStatusCode)
{
var sResponse_content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<oResult>(sResponse_content);
}
else
{
return oResult;
}
}
catch (Exception ex)
{
LogFile(ex);
return oResult;
}
}
Please advice me if any issue from the source code.
Thank you
you should not trying serialize deserialize twice
remove from your code
var Data = JsonConvert.DeserializeObject(JSON_sObject);
and replace
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data);
with this
var content = new StringContent(JSON_sObject, Encoding.UTF8, "application/json");
var response = await client.PostAsync(sEnd_Url, content);
also fix base httpclient address
var baseUri= #"http://localhost:44340";
using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUri) };
try {

Unable to call two consecutive api methods, one for create a user and one for delete the created user

I'm having a problem while developing my api, i have some calls, like CreateUser, DeleteUser, GetAllUser etc. and no matter what, i cannot make consecutives create and delete user calls.
When i call the create user method, returning the user id, i cannot delete the newly created user, it will return a 404 not found status code.
I've tried with postman, using the runner collection, and it gives no errors, it works fine, so i think it's a problem with my api calls, and not with my controller method.
I've also tried to create a little console app for test (attached), following the example on the microsoft documentation, with no luck,
At this point i'm not sure what may be the problem, i tought about an sql problem, maybe it doesn't have time to create the row, before i delete it, but in postman works fine, so... , or maybe a problem with async calls, but i always wait for result, so i think it's fine.
static string _basicAuthenticationUser = "UserTest";
static string _basicAuthenticationPassword = "Password";
static string _email = "user#gmail.com";
static string _password = "test";
static UtentiApiModel userToCreate =
new UtentiApiModel
{
Nome = "Alex",
Cognome = "Hello",
Email = "user#gmail.com",
Password = "test",
};
static HttpClient client = new HttpClient();
static void Main(string[] args)
{
var authValue = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_basicAuthenticationUser}:{_basicAuthenticationPassword}")));
client = new HttpClient()
{
DefaultRequestHeaders = { Authorization = authValue }
};
RunAsync().GetAwaiter().GetResult();
}
private static async Task RunAsync()
{
client.BaseAddress = new Uri("http://localhost:1045/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var id = await CreateUserAsync(userToCreate);
var statusCode = await DeleteUserAsync(id);
Console.WriteLine(statusCode.ToString());
Console.ReadKey();
}
static async Task<long> CreateUserAsync(UtentiApiModel utente)
{
var json = JsonConvert.SerializeObject(utente);
var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(
"test/", content);
response.EnsureSuccessStatusCode();
var reslt = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<UtentiApiModel>(reslt).Id;
}
static async Task<HttpStatusCode> DeleteUserAsync(long id)
{
HttpResponseMessage response = await client.DeleteAsync(
"/test/"+id+");
return response.StatusCode;
}

Can't make Post requests to Web API

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
}

c# HttpClient PostAsync with async and await not working

I am running into a deadlock situation when trying to post to WebApi 2 from WebApi 1 using HttpClient PostAsync and using async and await.
Below is WebAPI 1:
public HttpResponseMessage Get([FromUri]int oid)
{
var orderdetails = _orderServices.GetOrderDetails(oid);
var xml = new XmlMediaTypeFormatter();
xml.UseXmlSerializer = true;
string orderdetailsser = Serialize(xml, orderdetails);
var result = PostXml(orderdetailsser);
return Request.CreateResponse(HttpStatusCode.OK);
}
public static async Task<HttpResponseMessage> PostXml(string str)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:58285/");
var content = new StringContent(str);
var response = await client.PostAsync("api/default/ReceiveXml", content).ConfigureAwait(false);
return response;
}
}
And WebApi2:
[System.Web.Http.HttpPost]
public HttpResponseMessage ReceiveXml(HttpRequestMessage request)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(request.Content.ReadAsStreamAsync().Result);
xmlDoc.Save(#"C:\xmlfiles\xml2.xml");
XmlSerializer deserializer = new XmlSerializer(typeof(OrderInfoModel));
TextReader reader = new StreamReader(#"C:\xmlfiles\xml2.xml");
object obj = deserializer.Deserialize(reader);
OrderInfoModel orderdetails = (OrderInfoModel)obj;
reader.Close();
var patient_id = _patientServices.ProcessPatient(orderdetails.Patient, orderdetails.OrderInfo);
var orderid = _orderServices.ProcessOrder(orderdetails.Patient, orderdetails.OrderInfo, patient_id);
if (orderdetails.OrderNotes != null && orderdetails.OrderNotes.Count() > 0)
{
var success = _orderServices.ProcessOrderNotes(orderid, orderdetails.OrderNotes);
}
var prvid = _orderServices.ProcessOrderProvider(orderid, orderdetails.ReferringProvider);
var shpngid = _orderServices.ProcessOrderShipping(orderid, orderdetails.ShippingInfo);
var payerid = _orderServices.ProcessOrderPayer(orderid, orderdetails.Insurances);
return Request.CreateResponse(HttpStatusCode.OK, orderid);
}
I am not getting any response back to WebAPI 1 from WebAPI 2. I have gone through several articles online about deadlock situation. However, I am unable to resolve the deadlock in my case. What am I doing wrong here? Am I using async and await properly?
To build off my comment above, modify your code so that you are not blocking on an async operation. Additionally _orderServices.GetOrderDetails(oid); sounds like a method that hits a database and as such should be await _orderServices.GetOrderDetailsAsync(oid); wherein you use the whatever async api is available for your database access.
[HttpGet()]
public async Task<HttpResponseMessage> Get([FromUri]int oid) {
var orderdetails = _orderServices.GetOrderDetails(oid);
var xml = new XmlMediaTypeFormatter();
xml.UseXmlSerializer = true;
string orderdetailsser = Serialize(xml, orderdetails);
var result = await PostXml(orderdetailsser);
return Request.CreateResponse(HttpStatusCode.OK);
}
public static async Task<HttpResponseMessage> PostXml(string str) {
using(var client = new HttpClient()) {
client.BaseAddress = new Uri("http://localhost:58285/");
var content = new StringContent(str);
var response = await client.PostAsync("api/default/ReceiveXml", content).ConfigureAwait(false);
return response;
}
}
[HttpPost()]
public async Task<HttpResponseMessage> ReceiveXml(HttpRequestMessage request) {
var xmlDoc = new XmlDocument();
xmlDoc.Load(await request.Content.ReadAsStreamAsync());
xmlDoc.Save(#"C:\xmlfiles\xml2.xml");
XmlSerializer deserializer = new XmlSerializer(typeof(OrderInfoModel));
TextReader reader = new StreamReader(#"C:\xmlfiles\xml2.xml");
object obj = deserializer.Deserialize(reader);
OrderInfoModel orderdetails = (OrderInfoModel)obj;
reader.Close();
var patient_id = _patientServices.ProcessPatient(orderdetails.Patient, orderdetails.OrderInfo);
var orderid = _orderServices.ProcessOrder(orderdetails.Patient, orderdetails.OrderInfo, patient_id);
if(orderdetails.OrderNotes != null && orderdetails.OrderNotes.Count() > 0) {
var success = _orderServices.ProcessOrderNotes(orderid, orderdetails.OrderNotes);
}
var prvid = _orderServices.ProcessOrderProvider(orderid, orderdetails.ReferringProvider);
var shpngid = _orderServices.ProcessOrderShipping(orderid, orderdetails.ShippingInfo);
var payerid = _orderServices.ProcessOrderPayer(orderid, orderdetails.Insurances);
return Request.CreateResponse(HttpStatusCode.OK, orderid);
}
Resources
Don't Block on Async Code
Avoid Async Void

PostAsync parameter is always null

I am calling an API Post method, however, I am not sure what I am doing wrong but the value in the API is always null. The method I am calling the API from is below. When I hit this I can see Ids is list of ints with 5 values for example.
private void Save(List<int> Ids)
{
var myAPI = ConfigurationManager.AppSettings["MyAPI"];
string myIds = string.Join(",", Ids);
using (var client = new HttpClient())
{
int result = client.PostAsync(myAPI, new { test = myIds }, new JsonMediaTypeFormatter())
.Result
.Content
.ReadAsAsync<int>()
.Result;
}
}
My API signature is like below - with a breakpoint on I can see it is getting hit but test the parameter I am trying to pass is always null
[HttpPost]
[Route("api/MyController/SaveData")]
public HttpResponseMessage SaveData([FromBody]List<string> test)
{
try
{
//Rest of method removed for brevity
I have tried removing the [FromBody] Annotation from the WebAPI controller but test still is getting null with breakpoint in the SaveData API method
Try this:
private void Save(List<int> Ids)
{
var myAPI = ConfigurationManager.AppSettings["MyAPI"];
using (var client = new HttpClient())
{
var requestBody = JsonConvert.SerializeObject(Ids);
var postRequest = new StringContent(requestBody, Encoding.UTF8, "application/json");
var response = client.PostAsync(myAPI, postRequest).GetAwaiter().GetResult();
var rawResponse = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
// Do something with the answer
}
}
I also suggest to make the method private Task Save and replace .GetAwaiter().GetResult(); with await in front of that calls.
In my case i used System.Web.Http.ApiController instead of System.Web.Mvc.Controller. So over all code looks like
public class YourAppController : ApiController
{
[System.Web.Http.Route("publish-message")]
public HttpResponseMessage Post([System.Web.Http.FromBody] string msges)
{
//Your Code
return Request.CreateResponse(HttpStatusCode.OK, "");
}
}
public async Task<string> PublishMessageCall(string publishMessage){
var returnval = "";
string httpWebRqst = "http://localhost:543134535/publish-message";
using (HttpClient myClient = new HttpClient())
{
var jsonString = JsonConvert.SerializeObject(publishMessage);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await myClient.PostAsync(httpWebRqst, content);
var responseString = await response.Content.ReadAsStringAsync();
}
return await Task.FromResult(returnval);}

Categories

Resources