Calling external HTTP service using HttpClient from a Web API Action

Aha, I needed to do the following (return a Task rather then void): // GET api/values public async Task<IEnumerable<string>> Get() { var result = await GetExternalResponse(); return new string[] { result, “value2” }; } private async Task<string> GetExternalResponse() { var client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(_address); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsStringAsync(); … Read more

How can I get System.Net.Http.HttpClient to not follow 302 redirects?

One of the overloads of the HttpClient constructor takes a WebRequestHandler argument. The HttpClient class uses this WebRequestHandler for sending requests. The WebRequestHandler class provides a property called AllowAutoRedirect to configure the redirect behaviour. Setting this property to false instructs the HttpClient to not follow redirect responses. Here is a small code sample: WebRequestHandler webRequestHandler … Read more

DelegatingHandler for response in WebApi

Yes. You can do that in the continuation task. I explain it here. For example, this code (from the blog above) traces request URI and adds a dummy header to response. public class DummyHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // work on the request Trace.WriteLine(request.RequestUri.ToString()); var response = … Read more

How to send a file and form data with HttpClient in C#

Here’s code I’m using to post form information and a csv file using (var httpClient = new HttpClient()) { var surveyBytes = ConvertToByteArray(surveyResponse); httpClient.DefaultRequestHeaders.Add(“X-API-TOKEN”, _apiToken); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”)); var byteArrayContent = new ByteArrayContent(surveyBytes); byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse(“text/csv”); var response = await httpClient.PostAsync(_importUrl, new MultipartFormDataContent { {new StringContent(surveyId), “\”surveyId\””}, {byteArrayContent, “\”file\””, “\”feedback.csv\””} }); return response; } This is … Read more

How to disable Chunked Transfer Encoding in ASP.Net C# using HttpClient

It looks like you need to set the Content-Length header too, if you don’t it seems to use the MaxRequestContentBufferSize on HttpClientHandler to chunk the data when sending it. Try using a StringContent, ByteArrayContent or StreamContent (If the steam is seekable) as these will be able to calculate the length for you. var content = … Read more

HttpClient: The uri string is too long

If, like me, you’re faced with some wonky 3rd party web service that will only accept form content, you can work around the problem like this: // Let’s assume you’ve got your key-value pairs organised into a nice Dictionary<string, string> called formData var encodedItems = formData.Select(i => WebUtility.UrlEncode(i.Key) + “=” + WebUtility.UrlEncode(i.Value)); var encodedContent = … Read more

Should I cache and reuse HttpClient created from HttpClientFactory?

HttpClient is only IDisposable because its HttpMessageHandler is IDisposable. In reality, it’s the HttpMessageHandler which should be long-lived. HttpClientFactory works by keeping a long-lived HttpMessageHandler internally. Whenever you ask for a HttpClient, it uses the long-lived HttpMessageHander, and tells the HttpClient not to dispose it when the HttpClient is disposed. You can see that on … Read more

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