Should I await ReadAsStringAsync() if I awaited the response that I’m performing ReadAsStringAsync() on?

Your first example is the correct one. The second example does not yield during the asynchronous operation. Instead, by getting the value of the content.Result property, you force the current thread to wait until the asynchronous operation has completed. In addition, as commenter Scott Chamberlain points out, by blocking the current thread it is possible … Read more

Re-Send HttpRequestMessage – Exception

I wrote the following extension method to clone the request. public static HttpRequestMessage Clone(this HttpRequestMessage req) { HttpRequestMessage clone = new HttpRequestMessage(req.Method, req.RequestUri); clone.Content = req.Content; clone.Version = req.Version; foreach (KeyValuePair<string, object> prop in req.Properties) { clone.Properties.Add(prop); } foreach (KeyValuePair<string, IEnumerable<string>> header in req.Headers) { clone.Headers.TryAddWithoutValidation(header.Key, header.Value); } return clone; }

Using HttpClient.GetFromJsonAsync(), how to handle HttpRequestException based on HttpStatusCode without extra SendAsync calls?

You can use: // return HttpResponseMessage var res= await httpClient.GetAsync<List<Car>>(“/api/cars”) if (res.IsSuccessStatusCode) var cars = res.Content.ReadFromJsonAsync<List<Car>>(); else // deal with the HttpResponseMessage directly as you used to I use a base class like this: using System; using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; namespace MyProject.ClientAPI { public abstract class ClientAPI { protected readonly HttpClient Http; private … Read more

HttpClient with BaseAddress

In the BaseAddress, just include the final slash: https://localhost:44302/AndonService.svc/. If you don’t, the final part of the path is discarded, because it’s not considered to be a “directory”. This sample code illustrates the difference: // No final slash var baseUri = new Uri(“https://localhost:44302/AndonService.svc”); var uri = new Uri(baseUri, “Layouts/1100-00277”); Console.WriteLine(uri); // Prints “https://localhost:44302/Layouts/1100-00277” // With … Read more

How to set the Content-Type header for an HttpClient request?

The content type is a header of the content, not of the request, which is why this is failing. AddWithoutValidation as suggested by Robert Levy may work, but you can also set the content type when creating the request content itself (note that the code snippet adds application/json in two places-for Accept and Content-Type headers): … Read more

Cancelling an HttpClient Request – Why is TaskCanceledException.CancellationToken.IsCancellationRequested false?

That’s the case because HttpClient internally (in SendAsync) is using a TaskCompletionSource to represent the async operation. It returns TaskCompletionSource.Task and that’s the task you await on. It then calls base.SendAsync and registers a continuation on the returned task that cancels/completes/faults the TaskCompletionSource‘s task accordingly. In the case of cancellation it uses TaskCompletionSource.TrySetCanceled which associates … Read more

How to Refresh a token using IHttpClientFactory

Looks like you need DelegatingHandler. In two words you can “intercept” your http request and add the Authorization header, then try to execute it and if token was not valid, refresh token and retry one more time. Something like: public class AuthenticationDelegatingHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var … Read more

C# HttpClient.SendAsync throw “An error occurred while sending the request” exception when testing some URLs

If you look at the InnerException you will see that: “The remote name could not be resolved: ‘www.fc.edu’” This URL does not work on my browser either. In order to get an HTTP response you need the client to be able to communicate with the server (even in order to get error 404) and in … Read more

The request message was already sent. Cannot send the same request message multiple times

You are calling the same func parameter twice: var response = await ProcessRequestAsync(func); //… response = await ProcessRequestAsync(func); In this case func returns the same request every single time. It doesn’t generate a new one every time you call it. If you truly need a different request each time then func needs to return a … Read more

How to read cookies from HttpResponseMessage?

The issue I have with many of the answers here is that using CookieContainer uses short-lived HttpClient objects which is not recommended. Instead, you can simply read the “Set-Cookie” header from the response: // httpClient is long-lived and comes from a IHttpClientFactory HttpResponseMessage response = await httpClient.GetAsync(uri); IEnumerable<string> cookies = response.Headers.SingleOrDefault(header => header.Key == “Set-Cookie”).Value; … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)