dotnet / dotnet/aspnetcore

configureClient can not work with public class WeatherForecastController (HttpClient httpClient): ControllerBase

Open
#54,798 3 comments 0 reactions 0 assignees View on GitHub
area-mvc Needs: Attention :wave:
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

[Typed clients](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-8.0)

### Expected Behavior

```
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.

//configureClient can not work with public class WeatherForecastController (HttpClient httpClient): ControllerBase
//only work with public class public class GitHubService
builder.Services.AddHttpClient((sp, c) =>
{
var baseUrl = builder.Configuration[WebHostDefaults.ServerUrlsKey];
c.BaseAddress = new Uri(baseUrl);
});

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();
}
}
```
```
[ApiController]
[Route("[controller]/[action]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger _logger;
private readonly HttpClient _httpClient;

public WeatherForecastController(ILogger logger, HttpClient httpClient)
{
_logger = logger;
_httpClient = httpClient;
if (httpClient.BaseAddress == null) throw new ArgumentNullException();
}
}
```

### Steps To Reproduce

_No response_

### Exceptions (if any)

_No response_

### .NET Version

8.0

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.