【问题标题】:How to create instance of service bound HttpClient?如何创建服务绑定 HttpClient 的实例?
【发布时间】:2020-02-05 22:54:07
【问题描述】:

我的服务中托管了 Identity Server 4。它公开了各种端点,我想从同一服务访问token 端点。 它没有暴露任何接口,所以我可以将它作为依赖注入,因此我必须发出一个 http 请求。

现在我像这样设置HttpClient 的网址:

var req = _contextAcessor.HttpContext.Request;
var baseAddr = $"{req.Scheme}://{req.Host}";
client.BaseAddress = new Uri(baseAddr);

var addr = _urlHelperProvider.GetUrlHelper().Content("~/connect/token");

我不喜欢它,因为这里甚至没有使用 localhost。但是服务可能绑定到本地主机上的不同端口,我不知道如何获取传递给UseUrls方法的url列表。

理想情况下,我希望将客户端实例绑定到我的服务,类似于它与 WebApplicationFactory.CreateClient 方法的工作方式。

【问题讨论】:

  • 解析时遇到问题——您是在问如何在 DI 容器中注册配置绑定的 HttpClient 吗?
  • 不,我如何获取 BaseAddress 指向我的服务的 http 客户端?或者带有处理程序的 http 客户端,它甚至不使用网络,但只使用内存。
  • 如果您与 Identity Server 4 处于同一进程中,您是否探索过使用 IdentityServerTools 在内部生成令牌?见docs.identityserver.io/en/latest/topics/tools.html
  • @Richard 是的,同样的过程。我查看了工具,它们只是用于发布令牌,但端点做得更多。它不仅与 IS4 有关,还与托管在同一进程中并且可以在内存中访问的所有其他内容有关。
  • 我不确定我是否拥有您真正需要的东西,但可能类似于 IdentityServer4.Extensions 命名空间中的 public static string GetIdentityServerBaseUrl(this HttpContext context)。如您所见,这是 HttpContext 的扩展方法,因此可以通过以下方式从任何控制器调用它:HttpContext.GetIdentityServerBaseUrl()

标签: c# identityserver4 asp.net-core-3.0


【解决方案1】:

希望在这里找到答案,但最终得到了解决 所以希望这可能对某人有所帮助

创建客户端时,使用 https 设置主机通常会很有帮助 它应该等于在本地运行应用程序时默认拥有的任何主机

_factory = new WebApplicationFactory<Startup>().WithWebHostBuilder(BuildHost);
        Client = _factory.CreateClient(new WebApplicationFactoryClientOptions()
        {
            BaseAddress = new System.Uri("https://localhost:5031")
        });

那么你的要求很简单:

var parameters = new Dictionary<string, string> { { "grant_type", "client_credentials" },
            { "scope", "SomeScope" }, 
            { "client_id", "YourClientId" }, { "client_secret", "yoursecret" } };


        var encodedContent = new FormUrlEncodedContent(parameters);

        var response = await Client.PostAsync("/connect/token", encodedContent);

已经在本地测试过,它可以工作 如果您的设置仍有任何问题,请告诉我, 应该可以帮忙

【讨论】:

    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    相关资源
    最近更新 更多