在C#中从ASP.NET页将NetworkCredential传递给HttpWebRequest

jyztefdp  于 2023-10-21  发布在  .NET
关注(0)|答案(4)|浏览(181)

我试图使用HTTPWebRequest访问Web服务,但在传递凭据时遇到问题,请参阅下面的代码。我可以看到credentials对象nc正在调试器中构建,也可以在request.credentials的赋值中构建,但是当我到达最后一行代码时,它出现错误,并显示一条未授权的错误消息。我已经让我们的服务器人员在服务器上查看了请求,没有任何凭据被传递。是我在Credentials对象上做错了什么,还是有什么我需要做但没有在这里做的事情?

Uri requestUri = null;
Uri.TryCreate("https://mywebserver/webpage"), 
    UriKind.Absolute, out requestUri);

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create
    (requestUri);

NetworkCredential nc =
    new NetworkCredential("user", "password");

request.Credentials = nc;

request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
vuktfyat

vuktfyat1#

NetworkCredentials要么非常不直观,要么非常不直观,或者两者兼而有之。无论如何,您可以通过完全绕过NetworkCredentials并使用此方法(我在www.example.com上找到的)来解决这个问题mark.michaelis.net。

/* http://mark.michaelis.net/Blog/CallingWebServicesUsingBasicAuthentication.aspx */
byte[] credentialBuffer = new UTF8Encoding().GetBytes(username + ":" +password);
req.Headers["Authorization"] ="Basic " + Convert.ToBase64String(credentialBuffer);

因此,您所做的就是手动为HttpWebRequest创建一个头,并插入基本身份验证头中显示的内容。很管用。

67up9zun

67up9zun2#

Microsoft Premier Support最终帮助我解决了这个问题,它使用CredentialCache类添加了Credentials和“Basic”授权:

NetworkCredential nc =
    new NetworkCredential(GetSetting("username"), GetSetting("password"));
CredentialCache cache = new CredentialCache();

cache.Add(requestUri, "Basic", nc);

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
kzmpq1sx

kzmpq1sx3#

它帮助了我(对于Unity3d mono,而不是ASP.NET):

request.PreAuthenticate = true;

不需要手动设置Authorization头或使用CredentialCache。

f1tvaqid

f1tvaqid4#

有点离题,但直接相关,因为我在.NET 7中使用HttpClient。此代码片段显示如何获取用于REST API身份验证的Windows凭据。

// MS says just just instantiate this once and use
//  that instance until you're done. So, module var
private static HttpClient _HttpCli;

HttpClientHandler hand;
hand = new HttpClientHandler();
hand.UseDefaultCredentials = true;
hand.PreAuthenticate = true;
_HttpCli = new HttpClient(hand);

相关问题