C# HttpWebRequest - 预验证 : Still returns 401 forbidden (HTTPS)

标签 c# authentication httpwebrequest

我想请您帮助我快速编写以下代码,因为我总是收到“403 FORBIDDEN”。

HttpWebRequest pozadavek = (HttpWebRequest)WebRequest.Create("LINK THAT ASKS FOR AUTHLOGIN"); //https
    System.IO.StreamReader stream = null;
    System.String result = null;
    public Form1()
    {
        InitializeComponent();
        pozadavek.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
        pozadavek.Credentials = new NetworkCredential("NAME", "PASS");
        pozadavek.PreAuthenticate = true;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        WebResponse webresponse = pozadavek.GetResponse(); //throws an exception:403 forbidden
        stream = new System.IO.StreamReader(webresponse.GetResponseStream());
        result = stream.ReadToEnd();
        this.webBrowser1.DocumentText = result;
    }

最佳答案

您尝试打开的网站需要基本身份验证。最重要的是,您需要在您的请求中包含以 base64 编码的用户名/密码。幸运的是,.Net 可以为您做到这一点。像这样构建您的请求:

var credCache = new CredentialCache();
credCache.Add(new Uri("https://is.vsfs.cz/auth"), "Basic",
                  new NetworkCredential("user", "pwd"));
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = credCache;

Here's one article更详细地解释 .Net 中如何处理各种身份验证方案。

关于C# HttpWebRequest - 预验证 : Still returns 401 forbidden (HTTPS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2220297/

相关文章:

c# - mvc 根据模型值更改表列颜色

c# - INotifyPropertyChanged 实现,绑定(bind)不起作用

c# - 没有注册类型 'Microsoft.AspNetCore.Mvc..."的服务

svn - SVN客户端在哪里存储用户认证数据?

authentication - OAuth 2.0 服务到服务身份验证和最佳实践

c# - 无法修复 "Could not create SSL/TLS secure channel"发出 web 请求

c# - iOS 在执行过程中丢弃任务

php - IP session 绑定(bind)的替代方案

.net - 我可以重用 HttpWebRequest 吗?

c# - 通过 SSL 的 HttpWebRequest?