【问题标题】:Converting code from RestSharp to HttpClient将代码从 RestSharp 转换为 HttpClient
【发布时间】:2017-11-23 04:17:51
【问题描述】:

有人可以帮我将这个使用 RestSharp 的 ASP .Net Core 示例(用于我的 Web Api 以使用来自 Auth0 的管理 API)转换为使用 HttpClient 的示例吗?

var client = new RestClient("https://YOUR_AUTH0_DOMAIN/oauth/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\"grant_type\":\"client_credentials\",\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"audience\": \"https://YOUR_AUTH0_DOMAIN/api/v2/\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

我一直在挣扎……我有这个:

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://YOUR_AUTH0_DOMAIN/oauth/token");

但我不确定其余的...谢谢

【问题讨论】:

    标签: c# restsharp asp.net-core-webapi asp.net-core-1.1


    【解决方案1】:

    您需要获取请求正文并创建要发布的内容

    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.BaseAddress = new Uri("https://YOUR_AUTH0_DOMAIN/oauth/token");
    
    var json = "{\"grant_type\":\"client_credentials\",\"client_id\": \"YOUR_CLIENT_ID\",\"client_secret\": \"YOUR_CLIENT_SECRET\",\"audience\": \"https://YOUR_AUTH0_DOMAIN/api/v2/\"}"
    var content = new StringContent(json, Encoding.UTF8, "application/json");
    
    var response = await client.PostAsync("", content);
    

    【讨论】:

    • 我相信你知道,但它可能值得一提给 OP(因为帖子中没有结构,很难说明)。为每个请求新建一个 HttpClient 实例是个坏主意,最好在一个类中使用共享的 HttpClient 对象。
    • @maccettura 是的。我知道,值得一提。
    猜你喜欢
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多