.Net Core C#使用HttpClientFactory发送请求时如何添加参数?

问题描述 投票:0回答:1

使用HttpClient发送请求时如何添加参数?

我的目标 API 有问题;它需要两个参数,我需要弄清楚如何向我的请求添加两个参数。有人可以解释一下我如何使用 HttpClient 进行该调用吗?

我要调用的目标 API 的签名如下所示:

public string Authentication(string UN, string AP)

这是在我的startup.cs中:

services.AddHttpClient("Authentication", APIHttpClient =>
{
    APIHttpClient.BaseAddress = new Uri("Target API address");
}).ConfigurePrimaryHttpMessageHandler(() =>
    new HttpClientHandler
    {
        UseCookies = false
    }
);

在我的课堂上:

public class MyService 
{
   private IHttpClientFactory _clientFactory;

   public MyService(IHttpClientFactory httpClientFactory){
       _clientFactory = httpClientFactory;
   }

   public MyMethod(){

       HttpClient httpClient 
       _httpClientFactory.CreateClient("Authentication");
       
       // I need to add parameter here
   }
}


希望有人能告诉我如何编码,谢谢!

c# .net httprequest httpclient httpclientfactory
1个回答
0
投票

HttpclientFactory
不能替代
HttpClient
,工厂是创建 HttpClient 实例的一种方法。 最后你仍然可以使用
HttpClient
,微软的例子:

using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Shared;

namespace BasicHttp.Example;

public sealed class TodoService(
    IHttpClientFactory httpClientFactory,
    ILogger<TodoService> logger)
{
    public async Task<Todo[]> GetUserTodosAsync(int userId)
    {
        // Create the client
        using HttpClient client = httpClientFactory.CreateClient();
        
        try
        {
            // Make HTTP GET request
            // Parse JSON response deserialize into Todo types
            Todo[]? todos = await client.GetFromJsonAsync<Todo[]>(
                $"https://jsonplaceholder.typicode.com/todos?userId={userId}",
                new JsonSerializerOptions(JsonSerializerDefaults.Web));

            return todos ?? [];
        }
        catch (Exception ex)
        {
            logger.LogError("Error getting something fun to say: {Error}", ex);
        }

        return [];
    }
}

文档

© www.soinside.com 2019 - 2024. All rights reserved.