C# “如何修复”;状态代码:401,原因短语:';未经授权'&引用;错误
我得到下面的错误C# “如何修复”;状态代码:401,原因短语:';未经授权'&引用;错误,c#,asp.net,.net,asp.net-mvc,.net-core,C#,Asp.net,.net,Asp.net Mvc,.net Core,我得到下面的错误 {StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Transfer-Encoding: chunked Date: Mon, 05 Aug 2019 19:38:00 GMT Server: Kestrel X-Powered-By: ASP.NET }} 这是我使用的代码 stat
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Date: Mon, 05 Aug 2019 19:38:00 GMT
Server: Kestrel
X-Powered-By: ASP.NET
}}
这是我使用的代码
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var paras = new Dictionary<string, string>
{
{"Authorization", "042a9ff198c04caf99161406f46e|API Testing"},
{"Content-Type", "application/json"}
};
var response = client.PostAsync("https://tsrvcis/cis-api/get-jrsc?format=json", new FormUrlEncodedContent(paras)).Result;
Debug.WriteLine(response);
}
static void Main(字符串[]args)
{
ServicePointManager.SecurityProtocol=SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpClient=新的HttpClient();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
var=新字典
{
{“授权”、“042a9ff198c04caf99161406f46e | API测试”},
{“内容类型”,“应用程序/json”}
};
var response=client.PostAsync(“https://tsrvcis/cis-api/get-jrsc?format=json“,新格式URLENCODCONTENT(第段))。结果;
Debug.WriteLine(响应);
}
尽管此处的授权是正确的,但我仍然未经授权。如果正常情况下访问服务器需要登录,那么您可能希望尝试在HttpClient上使用NetworkCredentials
var httpClientHandler = new HttpClientHandler()
{
Credentials = new NetworkCredential(username, password, domainName),
};
var httpClient = new HttpClient(httpClientHandler);
// This is 10 seconds.
httpClient.Timeout = new TimeSpan(100000000);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Serialize the object
var serializedItem = new StringContent(
JsonConvert.SerializeObject(myUnserializedObject),
Encoding.UTF8,
"application/json");
var result = await httpClient.PostAsync(url, serializedItem);