0

I am adding HttpClient to DI as follows in my startup.cs

 services.AddHttpClient("main", x => { x.BaseAddress = new Uri("https://localhost:44342/"); x.DefaultRequestHeaders.Add("key", "value"); }); 

A little lower I add the validator to scope

services.AddTransient<IValidator<Domain.Form.Form>, Shared.Validators.Form.Form>();

The validator is defined as follows

public class Form : Base<Domain.Form.Form> { public Form(HttpClient httpClient) { RuleFor(x => x.Name).NotEmpty().MustAsync(async (name, cancellation) => { var rtrn = true; rtrn = !bool.Parse(await httpClient.GetStringAsync("api/forms/checkifnameexists?name=" + name)); return rtrn; }).When(x => x.Id == default).WithMessage("A form with the same name already exists"); } } 

The issue I am having is when the Validator hit, the HttpClient that is injected does not have the BaseAddress and headers set.

What am I doing wrong?

4
  • how is Form initialized? Typically, when using services.AddHttpClient, you should then be injecting an IHttpClientFactory that allows you to get the named instance, which you are not doing here. As a result, I would expect a completely unrelated HttpClient to be used Commented Aug 2, 2022 at 20:50
  • is class Form the same thing as Domain.Form.Form? Why do you have a class sharing the same name as its namespace? Commented Aug 2, 2022 at 20:51
  • You created a "named HttpClient" but you haven't properly set your Form class up to receive a named HttpClient. You should be getting named client instances from an IHttpClientFactory. Make sure you read the docs. Commented Aug 2, 2022 at 20:51
  • Also, inheritance should not be abused for the sake of common-functionality: whatever Base is, it looks like you're embuing a single class with both data-transfer and data-validation responsibility - this seems unwise. Commented Aug 2, 2022 at 20:52

1 Answer 1

2

As I mentioned in the comments, you are injecting a plain old HttpClient instance into Form, but you are registering a named client in your startup.

A recommended approach is to inject IHttpClientFactory into your instance, and then resolve your named client.

public class Form : Base<Domain.Form.Form> { public Form(IHttpClientFactory httpClientFactory) { RuleFor(x => x.Name).NotEmpty().MustAsync(async (name, cancellation) => { var httpClient = httpClientFactory.CreateClient("main"); var rtrn = true; rtrn = !bool.Parse(await httpClient.GetStringAsync("api/forms/checkifnameexists?name=" + name)); return rtrn; }).When(x => x.Id == default).WithMessage("A form with the same name already exists"); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.