Showing posts with label HttpClient. Show all posts
Showing posts with label HttpClient. Show all posts

Sunday, January 29, 2017

.NET JsonContent for HttpClient

.NET already comes with a nice collection of HttpContent serializers, but it lacks a JsonContent type. A common solution is to just serialize their payload to a JSON string and that insert that into an instance of StringContent. However, this means that you need to remember to set your headers, and it is a little bit inefficient because of how it creates multiple strings and buffers for each payload.

I have create a simple implementation of JsonContent that uses Json.NET and pooled memory streams. The result is between 2% and 10% faster, and causes ~50% fewer garbage collections.

Check out the implementation in Tact.NET:

Enjoy,
Tom

Saturday, October 31, 2015

How to change HttpClientHandler.AllowAutoRedirect

In the past I have talked about how the HttpClient is thread safe. This allows you to reuse the same HttpClient and be very efficient regarding how many ephemeral ports your application consumes.

Because the HttpClient and the HttpClientHandler both need to be thread safe, their properties become immutable after a request has been issued. If you are in a scenario where you need to change settings, such as whether or not the handler allows redirects, you will have to develop a little hack to work around the default behavior.

Below is a method where you can use reflection to set a private field and avoid the property setter from checking whether or not a request has been issued. This could cause thread safety issues, however with the current implementation of HttpCliehtHandler it is perfectly safe so long as only one thread is consume the client at a time.

HttpClientHandler Extension

public static class HttpClientHandlerExtensions
{
 private static readonly FieldInfo AllowAutoRedirectFieldInfo =
 typeof (HttpClientHandler).GetField(
 "allowAutoRedirect",
 BindingFlags.Instance | BindingFlags.NonPublic);
 public static void SetAllowAutoRedirect(this HttpClientHandler handler, bool value)
 {
 AllowAutoRedirectFieldInfo.SetValue(handler, value);
 }
}

Unit Test

public class HttpClientHandlerExtensionsTests
{
 [Fact]
 public async Task SetAllowAutoRedirectTest()
 {
 using (var handler = new HttpClientHandler())
 using (var client = new HttpClient(handler))
 {
 handler.AllowAutoRedirect = true;
 using (var response = await client.GetAsync("http://www.google.com"))
 response.EnsureSuccessStatusCode();
 Assert.Throws<InvalidOperationException>(() =>
 {
 handler.AllowAutoRedirect = false;
 });
 handler.SetAllowAutoRedirect(false);
 }
 }
}

Enjoy,
Tom

Sunday, March 8, 2015

HttpConnection Limit in .NET

Does your .NET application need to make a large number of HTTP requests concurrently? Be warned that the amount of simultaneous HTTP connections might get throttled by the .NET Framework. Often this can be a good thing, as it is a restriction that is designed to help protect an application from harming a larger system.

Don't worry, you can easily raise the connection limit by adding a simple Connection Management Section to your app.config or web.config:

<configuration>
 <system.net>
 <connectionManagement>
 <add address="*" maxconnection="10000" />
 </connectionManagement>
 </system.net>
</configuration>

Enjoy,
Tom

Saturday, November 29, 2014

.NET 4.5 HttpClient is Thread Safe

Good news everyone, the .NET 4.5 HttpClient is thread safe!

This means that you can share instances of your HttpClients across your entire application. This is useful in that it allows you to reuse persisted connections. One of the best ways to do this is to create a class that can manage the object lifetime of those clients for you.

Below is a simple HttpClientManager that will create one HttpClient per authority. Why per authority? Because you might have to have different settings or credentials for different websites.

Sample Unit Tests

public class HttpClientManagerTests
{
 [Fact]
 public void GetForAuthority()
 {
 using (var manager = new HttpClientManager())
 {
 var client1 = manager.GetForAuthority("http://tomdupont.net/");
 var client2 = manager.GetForAuthority("https://tomdupont.net/");
 Assert.Same(client1, client2);
 
 var client3 = manager.GetForAuthority("http://google.com/");
 Assert.NotSame(client1, client3);
 }
 }
 
 [Fact]
 public void TryRemoveForAuthority()
 {
 const string uri = "http://tomdupont.net/";
 
 using (var manager = new HttpClientManager())
 {
 Assert.False(manager.TryRemoveForAuthority(uri));
 
 manager.GetForAuthority(uri);
 
 Assert.True(manager.TryRemoveForAuthority(uri));
 
 }
 }
}

Saturday, August 16, 2014

System.Net.CredentialCache supports Digest Auth

In my last post I talked about implementing Digest Authentication in WebAPI. That was a server side implementation, but how do you make requests to that server? Good news: .NET's built in CredentialCache supports Digest Authentication!

PreAuthenticate

Be sure to enable PreAuthenticate, otherwise each request will require a new digest token have to make an additional two requests to get it! Do not worry, the request will not send your credentials without having a token first.

PreAuthenticate = false

PreAuthenticate = true

Subscribe to: Posts (Atom)

AltStyle によって変換されたページ (->オリジナル) /