HttpWebRequest-REST调用-身份验证失败,因为远程方已关闭传输流. [英] HttpWebRequest - REST Call -Authentication failed because the remote party has closed the transport stream.

查看:112
本文介绍了HttpWebRequest-REST调用-身份验证失败,因为远程方已关闭传输流.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

我正在连接到外部REST API(UK Companies house API以检索公司结果).这是使用c#中的HttpWebRequest类完成的,并部署在SharePoint之上.

I am connecting to an external REST API (UK Companies house API to retrieve company results). This is done using HttpWebRequest class in c# and deployed on top of SharePoint.

当我部署解决方案时,连接最初有效.但是几分钟后,它停止工作并给出以下错误.

When I deploy the solution, the connection intially works. But after few minutes It stop working and gives the below error.

身份验证失败,因为远程方已关闭传输流."

我的代码:

public CompanyProfile GetCompanyFromNumber(string companiesHouseNumber)
        {
            string url = "https://api.companieshouse.gov.uk/company/" + HttpUtility.HtmlEncode(companiesHouseNumber);

            string credentials = string.Format("{0}:{1}", ApiKey, ApiPassword);
            byte[] bytes = Encoding.ASCII.GetBytes(credentials);
            string base64 = Convert.ToBase64String(bytes);
            string authorization = string.Concat("Basic ", base64);

            CompanyProfile profile = null;

            try
            {
                // creates a web request
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
                ServicePointManager.ServerCertificateValidationCallback +=
                  (sender, certificate, chain, sslPolicyErrors) => true;
        ServicePointManager.SecurityProtocol =  SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;

                // use default credentials
                webReq.Proxy = _proxy;
                webReq.Headers.Add("Authorization", authorization);

                //webReq.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;

                // sets the method as a get
                webReq.Method = "GET";

                // performs the request and gets the response
                using (HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse())
                {
                    Console.WriteLine(webResp.StatusCode);

                    // prints out the server
                    Console.WriteLine(webResp.Server);

                    // create a stream to the response
                    var answer = webResp.GetResponseStream();
                    // read the stream
                    if (answer != null)
                    {
                        StreamReader streamReader = new StreamReader(answer);

                        string result = streamReader.ReadToEnd();
                        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(CompanyProfile));
                        profile = (CompanyProfile)ser.ReadObject(GenerateStreamFromString(result));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return profile;
        }

错误堆栈跟踪:

在System.Net.Security.SslState.StartReadFrame(字节[]缓冲区,Int32 readBytes,AsyncProtocolRequest asyncRequest)
在System.Net.Security.SslState.StartReceiveBlob(字节[]缓冲区,AsyncProtocolRequest asyncRequest)
在System.Net.Security.SslState.ForceAuthentication(布尔的receiveFirst,Byte []缓冲区,AsyncProtocolRequest asyncRequest)
在System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
在System.Threading.ExecutionContext.RunInternal(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔值saveSyncCtx)
在System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔值saveSyncCtx)
在System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态)中
在System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult结果)
在System.Net.TlsStream.Write(字节[]缓冲区,Int32偏移量,Int32大小)
在System.Net.ConnectStream.WriteHeaders(布尔异步)

Error Stack trace:

at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)

有什么想法会导致这种情况吗?有人面对过这个吗?一些互联网搜索显示我应该在下面进行此更改

Any idea what could be causing this? Has anyone faced this? Some internet search reveals that I should do this change below

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;

但是以上没有任何区别.非常感谢您的帮助.

But the above is not making any difference. Your help is much appreciated.

推荐答案

您好 sankumarr,

Hi sankumarr,

根据您的错误消息,该URL似乎仅支持TLS版本1.1和1.2.请添加以下代码,并检查其是否有效.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;

注意:请确保您使用的是Framework 4.5或更高版本,有关更多信息,请参阅:

最好的问候

可乐(Cole Wu)


这篇关于HttpWebRequest-REST调用-身份验证失败,因为远程方已关闭传输流.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆