c# - 如何将包含 --data-urlencode 的 curl 转换为 HttpClient 调用?
问题描述
我想知道如何将下面的 curl 调用转换为HttpClient
C# 中的 .NET Core 调用:
curl -X POST \
-d "client_id=client-id-source" \
-d "audience=client-id-target" \
-d "subject_token=access-token-goes-here" \
--data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
--data-urlencode "requested_token_type=urn:ietf:params:oauth:token-type:access_token" \
https://auth-dom/auth/realms/that-realm/protocol/openid-connect/token
到目前为止,我起草了类似的内容:
public static class MultipartFormDataContentExtensions
{
public static void AddStringContent(this MultipartFormDataContent content, string name, string value)
{
content.Add(new StringContent(value), name);
}
}
public static class Program
{
public static async Task Main(params string[] args)
{
const string url = "https://auth-dom/auth/realms/that-realm/protocol/openid-connect/token";
var content = new MultipartFormDataContent();
content.AddStringContent("client_id", "client-id-source");
content.AddStringContent("audience", "client-id-source");
content.AddStringContent("subject_token", "access-token-goes-here");
var httpClient = new HttpClient();
var response = await httpClient.PostAsync(url, content);
}
}
但我不知道--data-urlencode
在请求中是如何转换的,有什么想法吗?
解决方案
那里的答案有帮助:https ://stackoverflow.com/a/21989124/4636721
我最终只是使用纯FormUrlEncodedContent
文本作为内容:
常量字符串 url = " https://auth-dom/auth/realms/that-realm/protocol/openid-connect/token ";
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("subject_token", "access-token-goes-here"),
new KeyValuePair<string, string>("client_id", "client-id-source"),
new KeyValuePair<string, string>("audience", "client-id-target"),
new KeyValuePair<string, string>("client_id", "client-id-source"),
new KeyValuePair<string, string>("grant_type", "urn:ietf:params:oauth:grant-type:token-exchange"),
new KeyValuePair<string, string>("requested_token_type", "urn:ietf:params:oauth:token-type:access_token")
});
var httpClient = new HttpClient();
var response = await httpClient.PostAsync(url, content);
它工作得很好。
推荐阅读
- java - JavaFX - 从不同的场景将数据添加到 TableView
- angular - 单击警报按钮后如何重定向到当前页面
- c++ - UB 更改 const 指针的非 const 数据时
- c# - c# .Net Core 2.1 授权属性 - 默认声明
- python - 按索引条件过滤数组
- python - 如何在 python 上使用 RSA 私钥和 SHA256 进行解密
- java - 为什么更新大型数组的元素时,次要 GC 持续时间会发生如此大的变化?
- docker - 使用 docker-compose 挂载卷时出错
- json - 如何从json字符串中只获取一个属性值
- text - Applescript - 重复直到静态文本不等于值