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;
}
Related
A simple login method that works just fine until I shut down my API. Then the try-catch block acts as intended, and an exception is thrown and caught but, _response comes out with a status code of "200, OK". For the love of me, I can't figure out why. Please help!
The code looks so bad mainly because of all the patching and testing I am doing on it to figure out what is happening.
HttpResponseMessage response = null;
public async Task<HttpResponseMessage> login(AuthModel model)
{
HttpResponseMessage response = null;
model.responseMessage = "";
var client = new HttpClient();
string text = "{\"email\": \""+model.email+"\",\"password\": \""+model.password+"\"}";
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(_baseURL+"/api/user/login"),
Content = new StringContent(text, Encoding.UTF8, "application/json")
};
try
{
using (response = await client.SendAsync(request))
{
HttpResponseMessage _response = null;
//response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
//_response = response;
var body = await response.Content.ReadAsStringAsync();
var token = response.Headers.GetValues("auth-token").FirstOrDefault();
model.authToken = token;
model.name = body;
model.responseMessage = "Congratulations!";
return _response;
}
else
{
model.name = "";
model.responseMessage = await response.Content.ReadAsStringAsync();
return _response;
}
}
}
catch(Exception e) {
// model.responseMessage = e.Message;
return _response;
}
}
using "HttpResponseMessage _response = new HttpResponseMessage();" was setting the _response.StatusCode to be as "200" and the code was not dealing with that.
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 {
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'm executing an async POST request using a HttpClient in C#/Xamarin:
private async Task<string> ServicePostRequest (string url, string parameters)
{
string result = String.Empty;
using (var client = new HttpClient()) {
HttpContent content = new StringContent (parameters);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue ("application/x-www-form-urlencoded");
client.Timeout = new TimeSpan (0, 0, 15);
using(var response = await client.PostAsync(url, content)){
using (var responseContent = response.Content) {
result = await responseContent.ReadAsStringAsync ();
Console.WriteLine (result);
return result;
}
}
}
}
When I execute the following code, the expected result (JSON) is being logged correctly in the terminal:
Task<string> result = ServicePostRequest("http://www.url.com", "parameters");
Now, I would like to get this result into a variable to be able to parse it. However, when I use the following code, no result is being logged at all and the application is frozen:
Task<string> result = ServicePostRequest("http://www.url.com", "parameters");
string myResult = result.Result;
Also when I use the result.Wait() method, the application doesn't respond at all.
Any help would be highly appreciated.
Since ServicePostRequest is an awaitable method, change this:
Task<string> result = ServicePostRequest("http://www.url.com", "parameters");
string myResult = result.Result;
To:
string result = await ServicePostRequest("http://www.url.com", "parameters");
Side Note: Make sure the calling method is an Asynchronous method.
When I'm using DeleteAsync function in HttpClient (System.Net.Http) and retrieve the content with Content.ReadAsStringAsync() I always get null returned.
I've tried the same with GET, POST and PUT - and they always return some result.
Here is my code:
HttpClient _client = new HttpClient();
_client.BaseAddress = new Uri("http://httpbin.org/");
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = _client.DeleteAsync("/delete").Result;
string res = await response.Content.ReadAsStringAsync();
return await JsonConvert.DeserializeObjectAsync<T>(res);
I always get null returned.
However, all of this works:
GET:
HttpResponseMessage response = _client.GetAsync("/get").Result;
string res = await response.Content.ReadAsStringAsync();
return await JsonConvert.DeserializeObjectAsync<T>(res);
POST:
HttpResponseMessage response = _client.PostAsync("/post", new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")).Result;
string res = await response.Content.ReadAsStringAsync();
return await JsonConvert.DeserializeObjectAsync<T>(res);
PUT:
HttpResponseMessage response = _client.PutAsync("/put", new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")).Result;
string res = await response.Content.ReadAsStringAsync();
return await JsonConvert.DeserializeObjectAsync<T>(res);
But DeleteAsync() and ReadAsStringAsync() always return me null.
According to RFC you have to return body when returning status code 200 OK.
Your code never checks the message response for the StatusCode. Unlike WebClient, HttpClient does NOT throw when the StatusCode is not in the 2xx range.
I bet that if you check the HttpResponseMessage.StatusCode/HttpResonseMessage.ReasonPhrase values you will find that the server returned a code other than 200.
For example:
HttpClient _client = new HttpClient();
_client.BaseAddress = new Uri("http://httpbin.org/");
...
var response = await _client.DeleteAsync("/delete");
if (response.IsSuccessStatusCode)
{
var result=await response.Content.ReadAsStringAsync();
....
}
You can also call the EnsureSuccessStatusCode method to throw an exception if the response status is not a success code:
HttpClient _client = new HttpClient();
_client.BaseAddress = new Uri("http://httpbin.org/");
...
var response = await _client.DeleteAsync("/delete");
response.EnsureSuccessStatusCode();
var result=await response.Content.ReadAsStringAsync();
EDIT
By the way, running the following as is on .NET 4.5, returns a body:
var _client = new HttpClient();
_client.BaseAddress = new Uri("http://httpbin.org/");
var response = await _client.DeleteAsync("/delete");
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
Adding the Accept header doesn't make any difference
I have same case... for now I dont know method overload for DeleteAsync which accept content parameters like post. So I switch API from Delete to Post.
Do you know:
base_address + relative_address
"http://www.youdomain.com/myservice/" + "/test" = "/test".
This is why you get nothing