Why HttpClient.Post method is not Executing all the Methods? - c#

Here I wrote small function as
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Here im Calling one Private Methode
GetValiedSession("22");
if(1==1{
}
else
//SomeCode
GetValiedSession
public async Task<bool> GetValiedSession(string _SesToken)
{
string Baseurl = WebConfigurationManager.AppSettings["Baseurl"];
var values = new Dictionary<string, string>{
{ "securityToken","_SesToken"},
};
using (var client = new HttpClient())
{
var _json = JsonConvert.SerializeObject(values);
var content = new StringContent(_json, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsync(Baseurl + "validate/session", content);
var responseString = await response.Content.ReadAsStringAsync();
return false;
}
on the above code
var response = await client.PostAsync(Baseurl + "validate/session", content);
after this code its Executing if(1==1){---}
Please guide me how can I stop that until its execute.

Convert your Sync method to async If you can (This means you need to change your base method) and put change GetValiedSession("22"); to await GetValiedSession("22");
public override async Task OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Here im Calling one Private Methode
await GetValiedSession("22");
if(1==1{
}
else
//SomeCode
}
or simply use your method synchronously
GetValiedSession("22").GetAwaiter().GetResult();

Related

POST an empty body via HTTP Client

I am trying to send an empty body to a Post Request but it does not execute.
I have already tried this:
Post an empty body to REST API via HttpClient
static async Task<string> CancelSale(string mainUrl, string bearerInfo,string systemNumber)
{
var cancelsaleUrl = mainUrl + $"api/sale/cancel/{systemNumber}";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerInfo);
var data = new StringContent(null, Encoding.UTF8, "application/json");
var saleResponse = await client.PostAsync(cancelsaleUrl, data);
var responseBody = await saleResponse.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
return responseBody;
}
But it just does not execute, no exception.
I also tried this :
var saleResponse = await client.PostAsync(cancelsaleUrl, null);
which also does the same result.
Any ideas?
The problem was very simple. I had the result of whole this method in a variable and It did not await the method:
var cancelSale = CancelSale(mainUrl, bearerInfo, systemNumber);
Once it reaches anything that awaits it stops and leaves the method.
Here is the working code:
var cancelSale = await CancelSale(mainUrl, bearerInfo, systemNumber);
static async Task<string> CancelSale(string mainUrl, string bearerInfo,string systemNumber)
{
var cancelsaleUrl = mainUrl + $"api/sale/cancel/{systemNumber}";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerInfo);
var saleResponse = await client.PostAsync(cancelsaleUrl, null);
var responseBody = await saleResponse.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
return responseBody;
}

ASP.NET Api Client

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();

Correct way to create a new task and call asynchronously a web api c#

Hello i have created two examples but i am not sure if any of these are correct. I want to create a new task and call asynchronously a web api c#.Below there are both of the examples.
The first example:
private string APIResponse()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:55517/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/Values").Result;
if (response.IsSuccessStatusCode)
{
var products = response.Content.ReadAsStringAsync().Result;
//Thread.Sleep(5000);
return products.ToString();
}
else
{
return "ERROR";
}
}
protected async void Apibtn_Click(object sender, EventArgs e)
{
Task<string> task = new Task<string>(APIResponse);
task.Start();
var ApiResp = await task;
Do some work here...
// ...
//..
//.
}
And the second example is :
private async Task<string> APIResponse()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:55517/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/Values");
if (response.IsSuccessStatusCode)
{
var products = await response.Content.ReadAsStringAsync();
//Thread.Sleep(5000);
return products.ToString();
}
else
{
return "ERROR";
}
}
protected async void Apibtn_Click(object sender, EventArgs e)
{
Task<string> task = APIResponse();
// task.Start(); //You don't need to start the Tasks returned by
async method calls. They're started by default.
var ApiResp = await task;
//Do some work here...
//...
//..
//.
}
If none of the above is correct could you please give me an example? Thanks!
Your second example is almost correct, just do something like this instead:
private async Task<string> APIResponse()
{
using (HttpClient client = new HttpClient())
{
...
HttpResponseMessage response = await client.GetAsync("api/Values");
...
}
}
protected async void Apibtn_Click(object sender, EventArgs e)
{
var apiResp = await APIResponse();
}
Don't forget the using statement on IDisposable members (such as HttpClient)
The second example is correct; you should never use Task.Result.
However, there is no need for a separate task variable at the end; you can await the call directly.

C# HttpClient POST'ing Async

I want to send a http post that can take a couple of seconds to reply without freezing my UI, currently this code just hangs my application when the method is callled.
What am I doing wrong and how do i achieve my goal?
private async Task<string> DoHttpClientPost(string method, IDictionary<string, object> args = null)
{
{
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
handler.Proxy = null;
HttpResponseMessage response;
using (var myHttpClient = new HttpClient(handler))
{
myHttpClient.DefaultRequestHeaders.ExpectContinue = false;
myHttpClient.DefaultRequestHeaders.Add("Accept-Charset", "ISO-8859-1,utf-8");
myHttpClient.DefaultRequestHeaders.Add(APPKEY_HEADER, CustomHeaders.GetValues(APPKEY_HEADER));
myHttpClient.DefaultRequestHeaders.Add(SESSION_TOKEN_HEADER, CustomHeaders.GetValues(SESSION_TOKEN_HEADER));
myHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json-rpc"));
var call = new JsonRequest { Method = method, Id = 1, Params = args };
var jsonObject = JsonConvert.Serialize<JsonRequest>(call);
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json-rpc");
response = await myHttpClient.PostAsync(new Uri(EndPoint), content);
}
Console.WriteLine("\nCalling: " + method + " With args: " + JsonConvert.Serialize<IDictionary<string, object>>(args));
string jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse;
}
}
public T Invoke<T>(string method, IDictionary<string, object> args = null)
{
if (method == null)
throw new ArgumentNullException("method");
if (method.Length == 0)
throw new ArgumentException(null, "method");
var jsonString = DoHttpClientPost(method, args).Result;
var jsonResult = JsonConvert.Deserialize<JsonResponse<T>>(jsonString);
return jsonResult.Result;
}
var jsonString = DoHttpClientPost(method, args).Result;
This is your culprit. If you call .Result on a Task from the UI thread it will hang.
You'll need to async all the way up - so Invoke should be async and return a Task<T> and await the DoHttpClientPost call, the caller should be async etc. etc. etc.
You have to make two changes
Modify this line from
response = await myHttpClient.PostAsync(new Uri(EndPoint), content);
to
response = await myHttpClient.PostAsync(new Uri(EndPoint), content).ConfigureAwait(false);
And looks like your intention is to wait for the post call to complete and return the results, so modify this line from
var jsonString = DoHttpClientPost(method, args).Result;
to
var jsonStringTask = DoHttpClientPost(method, args);
jsonStringTask.Wait(); //wait for http post call to complete.
var jsonString = jsonStringTask.Result;

Accessing contents of HttpResponseMessage

I'd like to print the contents of a HTTPResponseMessage.
class Requests
{
public static async Task SendRequest(int port, string path, KVPairs kvPairs)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BASE_ADDRESS + port);
var request = new HttpRequestMessage(HttpMethod.Put, path);
request.Content = new FormUrlEncodedContent(kvPairs);
ProcessResponse(await client.SendAsync(request));
}
}
public static void ProcessResponse (HttpResponseMessage response)
{
Console.WriteLine(response.Content.ReadAsStringAsync());
}
}
SendRequest works perfectly. But ProcessResponse() prints System.Threading.Tasks.Task\`1[System.String]
How can I access and print the contents of the response? Thank you!
You need to await the task returned by response.Content.ReadAsStringAsync(), which in turn means you need to make ProcessResponse an async method, and await on that too. Otherwise, you are printing out the task object itself, which is not what you want.
Notice the 3 changes below (see comments):
public static async Task SendRequest(int port, string path, KVPairs kvPairs)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BASE_ADDRESS + port);
var request = new HttpRequestMessage(HttpMethod.Put, path);
request.Content = new FormUrlEncodedContent(kvPairs);
await ProcessResponse(await client.SendAsync(request)); // added await here
}
}
public static async Task ProcessResponse (HttpResponseMessage response) // added async Task here
{
Console.WriteLine(await response.Content.ReadAsStringAsync()); // added await here
}
This solution should work for you. Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern
You should use await or wait() to get the response and then process it like this:
var jsonString = response.Content.ReadAsStringAsync();
jsonString.Wait();
model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);

Categories

Resources