使用客户端凭据通过 SSL 进行 HttpWebRequest
我正在尝试使用 HttpWebRequest 获取需要用户名和密码的 https URI。 如果我将 URI 放入浏览器中,它会弹出一个对话框,要求提供凭据,然后就可以工作了。 使用 HttpWebRequest 给我一个 401 未经授权的错误。
NetworkCredentials 的文档说它不支持 SSL,但我找不到我应该使用的内容。
I'm trying to use HttpWebRequest to get an https URI that requires a username and password. If I put the URI into a browser it pops up a dialog asking for credentials and then works. Using HttpWebRequest gives me a 401 Unauthorized error.
The documentation for NetworkCredentials says it doesn't support SSL, but I can't find what I'm supposed to use.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
服务器使用 HTTP 基本身份验证还是其他类型? 如果使用 HTTP basic,则您可以将 Web 请求上的
Credentials
属性设置为包含正确用户名和密码的凭据,并将PreAuthenticate
属性设置为 true。下面是一个示例(未经测试,因此仅将其用作指南):
注意:根据我的经验,.NET 框架中存在一些奇怪的行为。 您可能认为它应该执行代码所说的操作,但它实际上是这样做的: 向
我不知道为什么它会这样做,因为它似乎坏了,所以也许这是我的机器的一个怪癖,也许它不会发生在你身上。
如果您的应用程序对性能不敏感,并且您的请求不是大数据的 POSTS,您可能不会注意到,但为了解决这个问题,我必须手动构建 HTTP 基本身份验证标头并将其设置在
通过操作
。Headers
集合手动处理 HttpWebRequestIs the server using HTTP basic authentication or some other kind? If it's using HTTP basic then you can set the
Credentials
property on the web request to a credential containing the correct username and password, and set thePreAuthenticate
property to true.Here's an example (it's untested, so use it as a guideline only):
Note: In my experience doing this, there is some odd behavior in the .NET framework. You'd think it should do what the code says, but it actually does this:
I have no idea why it would do this, as it seems broken, so perhaps it was a quirk of my machine and maybe it won't happen to you.
If your app is not performance sensitive, and your requests aren't POSTS of large data, you probably won't notice, but to get around it, I had to manually build the HTTP basic authentication header and set it on the
HttpWebRequest
manually by manipulating theHeaders
collection.