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

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

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

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

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

//It takes post call only
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 asp.net-core httprequest httpclient
1个回答
0
投票

如果api是POST请求,您可以发送带有如下参数的请求:

HttpClient httpClient = _clientFactory.CreateClient("Authentication");

// Create parameters
var parameters = new Dictionary<string, string>
{
    { "UN", "aa" },
    { "AP", "bbb" }
};

// Convert parameters to form-urlencoded content
var content = new FormUrlEncodedContent(parameters);

// Send POST request
var response = await httpClient.PostAsync("/auth", content);

API:

[HttpPost]
[Route("/auth")]
public string Authentication([FromForm]string UN, [FromForm]string AP)
{
    return UN;
}

如果api是GET请求:

HttpClient httpClient = _clientFactory.CreateClient("Authentication");

// Create query string with parameters
var queryString = new StringBuilder();
queryString.Append("?UN=").Append(Uri.EscapeDataString("aa"));
queryString.Append("&AP=").Append(Uri.EscapeDataString("bb"));

// Append query string to base URL
string requestUrl = "/auth" + queryString;

// Send GET request
var response = await httpClient.GetAsync(requestUrl);
© www.soinside.com 2019 - 2024. All rights reserved.