Search code examples
c#asp.netwebformsdotnet-httpclient.net-4.8

How to use HttpClient in asp.net webforms


I've spent quite a bit of time researching, but yet to find a reliable answer, so I'd like to start a fresh, new question.

What is the guidance for using the HttpClient class in an ASP.NET webforms based website? Note, this is not an MVC site, it's not .NET Core anything. It's an ASP.NET Webforms website. It is on the latest .NET Framework (4.8).

The technical challenge seems to be surrounding all the "you're doing it wrong" with HttpClient that leads to socket exhaustion. So the advice is to use dependency injection (presuming you're doing a .net core web app) or static instance (usually noted for console apps). But would you really declare a static variable for a webforms site (in App_Code or Global.asax)?

It seems incredible that to make use of any kind of REST API's, which is common, is so difficult to "get right."

The other challenge is that all its methods are async. However, I think that's doable after reading enough posts (and SO answers) from Stephen Cleary.

My main concern here, with HttpClient specifically, is it's proper usage (lifetime management, avoiding the socket exhaustion issue and also stale DNS issue with a "long lived" instance) in a webforms based website.


Solution

  • Quite simple really. Ignore the IDisposable interface it implements and create a single point/object like ExampleApiClient, from where you'll call it.

    Declare your member as:

    private static readonly HttpClient client = new HttpClient();
    

    And encapsulate its use by using it in a public function.

    There is a reason to create a new client though. If for example you want to call multiple different apis, with different proxies or default headers, create one for each api, but certainly not one for each request.