C#WebRequest检查页面是否需要HTTP身份验证


C# WebRequest Check if page requires HTTP Authentication

有人知道如何使用WebRequest类通过C#检查网页是否请求HTTP身份验证吗?我不是在问如何将凭据发布到页面,而是如何检查页面是否要求身份验证。

当前要获取HTML:的代码段

WebRequest wrq = WebRequest.Create(address);
wrs = wrq.GetResponse();
Uri uri = wrs.ResponseUri;
StreamReader strdr = new StreamReader(wrs.GetResponseStream());
string html = strdr.ReadToEnd();
wrs.Close();
strdr.Close();
return html;

PHP服务器端来源:

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Secure Sign-in"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

WebRequest.GetResponse返回类型为HttpWebResponse的对象。只要投射它,就可以检索StatusCode

但是,如果.Net收到状态为4xx或5xx的响应,它将给您一个例外(感谢您的反馈)。有一个小的变通方法,请查看:

    HttpWebRequest wrq = (HttpWebRequest)WebRequest.Create(@"http://webstrand.comoj.com/locked/safe.php");
    HttpWebResponse wrs = null;
    try
    {
        wrs = (HttpWebResponse)wrq.GetResponse();
    }
    catch (System.Net.WebException protocolError)
    {
        if (((HttpWebResponse)protocolError.Response).StatusCode == HttpStatusCode.Unauthorized)
        {
            //do something
        }
    }
    catch (System.Exception generalError)
    {
        //run to the hills
    }
    if (wrs.StatusCode == HttpStatusCode.OK)
    {
        Uri uri = wrs.ResponseUri;
        StreamReader strdr = new StreamReader(wrs.GetResponseStream());
        string html = strdr.ReadToEnd();
        wrs.Close();
        strdr.Close();
    }

希望这能有所帮助。

问候

可能想尝试

WebClient wc = new WebClient();
CredentialCache credCache = new CredentialCache();

如果你可以使用WebClient而不是WebRequest,你应该会有更高的级别,更容易处理标题等。

此外,可能需要检查此线程:System.Net.WebClient异常失败