Home > Enterprise >  Should I pass the full URL or just the domain to ServicePointManager.FindServicePoint()?
Should I pass the full URL or just the domain to ServicePointManager.FindServicePoint()?

Time:01-19

I've been reading about how to use HttpClient in .NET Framework.

The two main points I gathered was that HttpClient should be a singleton, and ServicePointManager.FindServicePoint() needs to be called in case of DNS changes.

But what do you pass to FindServicePoint()?

In this example, it passes the full URL:

var sp = ServicePointManager.FindServicePoint(new Uri("http://foo.bar/baz/123?a=ab"));
sp.ConnectionLeaseTimeout = 60*1000; // 1 minute

However, in this example, it only passes in the base URL:

Uri baseUri = new Uri("https://someresource.com");
...
ServicePointManager.FindServicePoint(baseUri).ConnectionLeaseTimeout = 60 * 1000;

The HttpClient instance will be making requests to different resources all from the same host (eg. domain.com/resourceA and domain.com/resourceB).

I've read this answer, however unfortunately I can't use it as we don't have DI set up in our project.

CodePudding user response:

It doesn't matter since only host (and port if not default) portion of url will be used. It makes sense, because ServicePoint manages connections, and only host and port are needed to define a connection to remote server. Documentation of ServicePoint says:

The ServicePoint class handles connections to an Internet resource based on the host information passed in the resource's Uniform Resource Identifier (URI). The initial connection to the resource determines the information that the ServicePoint object maintains, which is then shared by all subsequent requests to that resource.

If not convinced by the description, you can ensure that in source code:

private static string MakeQueryString(Uri address) => address.IsDefaultPort ?
    address.Scheme   "://"   address.DnsSafeHost :
    address.Scheme   "://"   address.DnsSafeHost   ":"   address.Port.ToString();

This is how lookup key for service point object is created when you call FindServicePoint method (only host and port are used).

So whether you pass "http://somehost.com" or "http://somehost.com/somepath?somequery=x" - result will be the same.

  • Related