【问题标题】:What would be a built-in alternative to using RestSharp for the following code?在以下代码中使用 RestSharp 的内置替代方法是什么?
【发布时间】:2021-04-13 18:37:51
【问题描述】:

我需要发送以下内容,但使用内置的 .net 类,最好是 HttpClient。

我尝试使用 Httpclient、HttpRequestMessage、HttpResponseMessage 和 SendAsync,但在使用 Postman 的相同参数调用它时,我得到了缺少 json 的错误。

也许我使用了错误的类。谢谢

    var client = new RestClient("myurl");
    var request = new RestRequest(Method.POST);
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("channelId", "mytestid");
    request.AddHeader("Authorization", "big access token");
    request.AddHeader("Content-Type", "application/json");
    request.AddHeader("Accept", "application/json");
    request.AddParameter("undefined", "{\n  \"jsonrequesthere\":...}", ParameterType.RequestBody);
    IRestResponse response = client.Execute(request);

【问题讨论】:

    标签: c# postman httprequest httpclient


    【解决方案1】:

    应该很简单

    var client = new HttpClient(); // ideally this would be created from IHttpClientFactory
    var request = new HttpRequestMessage(HttpMethod.Post, "myurl");
    
    request.Headers.Add("cache-control", "no-cache");
    request.Headers.Add("channelId", "mytestid");
    request.Headers.Add("Authorization", "big access token");
    request.Headers.Add("Accept", "application/json");
    
    request.Content = new StringContent(json, null, "application/json");
    // or request.Content = JsonContent.Create(SomeObjectToSerialize);
    
    var response = await client.SendAsync(request);
    var result = await response.Content.ReadAsStringAsync();
    

    注意:还有许多其他内置方法可以实现相同的目标。尽管在您学习的这个阶段,您最好只阅读文档

    Full Demo Here

    【讨论】:

    • 谢谢我以前这样做过,但当我意识到我传递了错误的 json 键时仍然失败......但是你的代码更干净,谢谢!
    • @RollRoll 都很好,很高兴它有帮助。还要记住,如果您尝试过某些东西,最好将其粘贴到问题中:)
    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多