Roslyn-analyzers: CA2234 should not be triggered on httpclient

Created on 24 Dec 2019  路  5Comments  路  Source: dotnet/roslyn-analyzers

Httpclient calls use string to add params or use basePath it does not make sense to append a base path with a Uri eg its suggesting http://localhost/service and append a Uri

Analyzer package

Microsoft.CodeAnalysis.FxCopAnalyzers

Package Version

v2.9.8 (Latest)

Diagnostic ID

Repro steps

  1. create a httpclient call get with a string param
    2.
    3.

Expected behavior

No message

Actual behavior

Area-Microsoft.NetCore.Analyzers Resolution-Answered help wanted

Most helpful comment

Hi @Evangelink . Thank you for pointing new Uri("/items", UriKind.Relative)! It did solve the issue. False alarm then. Sorry about that.

All 5 comments

I am not sure to understand why this is a false-positive. The rule suggests to use the Uri overload instead of the string one when available which is the case here. Could you please help me understand?

@bklooste @garyfawcett Would you mind giving me a little more context? I'd be happy to improve the rule but I currently fail to understand where the problem is.

@Evangelink Please correct me if I'm wrong. Here's an example:

// Configuring HttpClient with BaseAddress
services.AddHttpClient("my_client", client =>
{
  client.BaseAddress = new Uri("http://mybaseurl.com/path/");
});

...

// In a class, in which the IHttpClientFactory was injected
using var client = _httpClientFactory.CreateClient("my_client");
var result = await client.PostAsync("/items", content);

In such use case, in the last line I could not replace the argument "/items" with a Uri unless I rebuild the whole Uri (base address + "/items"). However, that last line gets flagged by CA2234. I too, have to consider it a false negative.

@corentinaltepe I am no expert with web client so there might be something I am missing. Can't you simply replace the last line with var result = await client.PostAsync(new Uri("/items", UriKind.Relative), content);?

Hi @Evangelink . Thank you for pointing new Uri("/items", UriKind.Relative)! It did solve the issue. False alarm then. Sorry about that.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

onyxmaster picture onyxmaster  路  3Comments

x3ntrix picture x3ntrix  路  3Comments

paulomorgado picture paulomorgado  路  3Comments

paulomorgado picture paulomorgado  路  3Comments

OmarTawfik picture OmarTawfik  路  3Comments