c# - Api 在提琴手中返回结果,但响应不是控制台中的结果
问题描述
我在 .net 核心控制台中运行此代码来调用 api:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
httpClientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
using (var httpClient = new HttpClient())
{
ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "****=");
httpClient.DefaultRequestHeaders.Add("PID", "****");
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "grant_type", "password" },
{ "username", "****" },
{ "password", "****" }
});
HttpResponseMessage response = httpClient.PostAsync("https://myurl", content).Result;
Console.WriteLine(response.ToString());
}
}
}
}
}
当我调用 API 时,我会检查提琴手以查看响应:
但是我的代码的结果是这样的:
StatusCode: 200, ReasonPhrase: '', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
requestid: 26d6ac8559744dd59b4ba77c590212e9
Cache-Control: no-store
Pragma: no-cache
Transfer-Encoding: chunked
Date: Wed, 20 Jan 2021 11:12:33 GMT
Server: PGSB
X-Powered-By: PGSB
X-Frame-Options: DENY
x-xss-protection: 1;mode=block
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000;includeSubDomains;preload
referrer-policy: no-referrer-when-downgrade
Content-Security-Policy: default-src https:; img-src https: data:; script-src 'self' 'unsafe-eval' 'unsafe-inline'; style-src 'self' 'unsafe-inline' report-uri https://pgsb.iran.gov.ir/actions/reportingEndpointForContentSecurityPolicy
Connection: close
Content-Type: application/json; charset=UTF-8
}
解决方案
阅读响应的内容
HttpResponseMessage response = await httpClient.PostAsync("https://myurl", content);
string json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json);
我还建议使代码异步并避免阻塞调用,例如.Result
class Program {
public static async Task Main(string[] args) {
//...
推荐阅读
- javascript - 具有名称的函数表达式中的匿名函数
- perl - 如何在 Mojo::Exception 检查块中重定向?
- json - 如何使用我的图像在本地的颤振解析 json 文件中的图像?
- python - 从没有 Pandas 推断标题的 csv 中读取特定列
- c# - 如何在具有嵌入式 C# 的 Blazor/Razor 页面中进行不区分大小写的字符串比较?
- functional-programming - 从 Fluture 为 Futures 创建 composePipe 函数
- reactjs - 在 React 中,我如何将有状态组件的某些方面转换为在函数组件中工作?
- python - 得到ValueError:'顶点'必须是形状为Nx2的二维列表或数组,当它是Nx2时?
- python - 如何在大型数据集上创建交互式图形?
- python-3.x - 带有“%%”参数的 Postgres 查询未通过 psycopg2 返回结果