c# - 在以下代码中使用 RestSharp 的内置替代方法是什么?
问题描述
我需要发送以下内容,但最好使用内置的 .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);
解决方案
应该很简单
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();
注意:还有许多其他内置方法可以实现相同的目标。尽管在您学习的这个阶段,您最好只阅读文档
推荐阅读
- javascript - 如何简化我的减速器功能或简单的减速器功能应该多长时间?
- ubuntu - 双击打开已经运行的 jupyter lab 的 .ipynb
- java - 如何使 java JFR 在转储 StartFlightRecording 文件名和时间戳的文件中包含时间戳
- c++ - EasyHook 停止捕获一些消息
- .net - Swagger 具有相同名称的不同 API 版本,相同的路由不起作用
- r - 如何在R中订购一个情节
- c# - 在 Blazor 的开始屏幕上设置 InputText 焦点
- pine-script - 如何用指标替换策略变量
- reactjs - 如何将 HTMLElement 转换为 React 元素?
- javascript - 将 css 半径更新为直线(附加 jsfiddle)