简体   繁体   English

.NET Rest API调用不起作用

[英].Net rest api call not working

I am trying to connect to a rest api which sends a json response. 我正在尝试连接到发送json响应的rest api。 When I copy paste the url in the browser.Browser gives a pop up to enter username and password. 复制时,将网址粘贴到浏览器中。浏览器弹出一个对话框,输入用户名和密码。

On entering the username and password (Active directory ID and password), service sends a JSON response. 输入用户名和密码(Active Directory ID和密码)后,服务将发送JSON响应。 Http request and Response Http请求和响应

But trying to connect from code, it returns the following error 但是尝试从代码连接时,它返回以下错误

{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Keep-Alive: timeout=15, max=100 Connection: Keep-Alive Date: Wed, 20 Apr 2016 11:38:45 GMT Server: Apache WWW-Authenticate: Basic realm="Login using your AD-ENT credentials, but do not prefix your ID with the domain" {StatusCode:401,ReasonPhrase:“未经授权”,版本:1.1,内容:System.Net.Http.StreamContent,标头:{Keep-Alive:超时= 15,最大= 100连接:Keep-Alive日期:4月20日,星期三2016 11:38:45 GMT服务器:Apache WWW-Authenticate:Basic realm =“使用您的AD-ENT凭据登录,但不要为您的ID加上域前缀”
Content-Length: 455 Content-Type: text/html; 内容长度:455内容类型:text / html; charset=iso-8859-1 }} charset = iso-8859-1}}

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(@"http://pro.abc.com/services/");

var authData = string.Format("{0}:{1}","username", "password");
var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);

HttpResponseMessage response = await client.GetAsync("reportpro/reports/11824");

The code was perfect, only issue was I was using http instead of https. 代码是完美的,唯一的问题是我使用的是HTTP而不是https。

When copy pasting the url in browser, browser was converting http to https. 在浏览器中复制粘贴网址时,浏览器正在将http转换为https。 Hence it worked perfectly in browser. 因此,它在浏览器中完美运行。

After changing http to https in code it worked perfectly. 在代码中将http更改为https后,它可以完美运行。

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(@"https://pro.abc.com/services/");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM