首页 > 解决方案 > 如何将包含 --data-urlencode 的 curl 转换为 HttpClient 调用?

问题描述

我想知道如何将下面的 curl 调用转换为HttpClientC# 中的 .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在请求中是如何转换的,有什么想法吗?

标签: c#curlpost.net-core

解决方案


那里的答案有帮助: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);

它工作得很好。


推荐阅读