401错误从代码中使用REST服务但在浏览器中工作 [英] 401 Error Consuming REST service from code but works in browser

查看:146
本文介绍了401错误从代码中使用REST服务但在浏览器中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从其他公司使用REST服务。当我在浏览器中使用链接时,它工作正常。但是从代码访问时我收到401错误。我究竟做错了什么?我是否需要在Web应用程序的web.config中添加内容?

  string  URL = < span class =code-string> @  https://hdapps-qa.homedepot.com/MYTHDPassport/rs/identity/isSessionValid?thdsso=TEST&callingProgram = PSC&安培;提交=提交; 
HttpWebRequest req = WebRequest.Create(URL)
as HttpWebRequest;
string result = null ;
req.Method = GET;
req.UseDefaultCredentials = true ;
req.PreAuthenticate = false ;
req.Credentials = CredentialCache.DefaultCredentials;
使用(HttpWebResponse resp = req.GetResponse()
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}

解决方案

想出来。如果会话无效,则REST服务返回响应代码401。所以我抓住了这个异常并处理它。感谢。

I am trying to consume a REST service from another company. When I use the link in the browser it works fine. However I get the 401 error when accessing from code. What am I doing wrong? Do I need to add something to the web.config of the web app?

string URL = @"https://hdapps-qa.homedepot.com/MYTHDPassport/rs/identity/isSessionValid?thdsso=TEST&callingProgram=PSC&Submit=Submit";
            HttpWebRequest req = WebRequest.Create(URL)
                                 as HttpWebRequest;
            string result = null;
            req.Method = "GET";
            req.UseDefaultCredentials = true;
            req.PreAuthenticate = false;
            req.Credentials = CredentialCache.DefaultCredentials;
            using (HttpWebResponse resp = req.GetResponse()
                                          as HttpWebResponse)
            {
                StreamReader reader =
                    new StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
            }

解决方案

Figured it out. The REST Service is returning a response code of 401 if the session is not valid. So I am catching that exception and handling it. Thanks.


这篇关于401错误从代码中使用REST服务但在浏览器中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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