相关疑难解决方法(0)

在ASP.Net Core中使用HTTPClient作为DI Singleton的最佳方法

我试图弄清楚如何最好地使用ASP.Net Core中的HttpClient类.

根据文档和几篇文章,该类最好在应用程序的生命周期中实例化一次,并为多个请求共享.不幸的是,我找不到如何在Core中正确执行此操作的示例,因此我提出了以下解决方案.

我的特殊需求需要使用2个不同的端点(我有一个用于业务逻辑的APIServer和一个API驱动的ImageServer),所以我的想法是拥有2个可以在应用程序中使用的HttpClient单例.

我在appsettings.json中配置了我的服务点,如下所示:

"ServicePoints": {
"APIServer": "http://localhost:5001",
"ImageServer": "http://localhost:5002",
}
Run Code Online (Sandbox Code Playgroud)

接下来,我创建了一个HttpClientsFactory,它将实例化我的2个httpclients并将它们保存在静态Dictionary中.

public class HttpClientsFactory : IHttpClientsFactory
{
    public static Dictionary<string, HttpClient> HttpClients { get; set; }
    private readonly ILogger _logger;
    private readonly IOptions<ServerOptions> _serverOptionsAccessor;

    public HttpClientsFactory(ILoggerFactory loggerFactory, IOptions<ServerOptions> serverOptionsAccessor) {
        _logger = loggerFactory.CreateLogger<HttpClientsFactory>();
        _serverOptionsAccessor = serverOptionsAccessor;
        HttpClients = new Dictionary<string, HttpClient>();
        Initialize();
    }

    private void Initialize()
    {
        HttpClient client = new HttpClient();
        // ADD imageServer
        var imageServer = _serverOptionsAccessor.Value.ImageServer;
        client.BaseAddress = new Uri(imageServer);
        HttpClients.Add("imageServer", client);

        // ADD apiServer …
Run Code Online (Sandbox Code Playgroud)

c# dotnet-httpclient asp.net-core

10
推荐指数
2
解决办法
7254
查看次数

如何使用带有IdentityServer4的ASP.Net标识添加要包含在access_token中的其他声明

如何添加要包含在令牌中的其他声明?

一旦API收到承载令牌,User.Identity对象就会填充以下声明.

[
  {
    "key": "nbf",
    "value": "1484614344"
  },
  {
    "key": "exp",
    "value": "1484615244"
  },
  {
    "key": "iss",
    "value": "http://localhost:85"
  },
  {
    "key": "aud",
    "value": "http://localhost:85/resources"
  },
  {
    "key": "aud",
    "value": "WebAPI"
  },
  {
    "key": "client_id",
    "value": "MyClient"
  },
  {
    "key": "sub",
    "value": "d74c815a-7ed3-4671-b4e4-faceb0854bf6"
  },
  {
    "key": "auth_time",
    "value": "1484611732"
  },
  {
    "key": "idp",
    "value": "local"
  },
  {
    "key": "role",
    "value": "AccountsManager"
  },
  {
    "key": "scope",
    "value": "openid"
  },
  {
    "key": "scope",
    "value": "profile"
  },
  {
    "key": "scope",
    "value": "roles" …
Run Code Online (Sandbox Code Playgroud)

asp.net-core identityserver4 asp.net-core-webapi asp.net-core-identity

9
推荐指数
1
解决办法
6219
查看次数