2

Webページが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>";
}
?>
4

2 に答える 2

4

WebRequest.GetResponseタイプのオブジェクトを返しますHttpWebResponse。キャストするだけで取得できますStatusCode

ただし、ステータス4xxまたは5xxの応答を受信した場合、.Netは例外を提供します(フィードバックに感謝します)。少し回避策があります、それをチェックしてください:

    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();
    }

お役に立てれば。

よろしく

于 2012-07-24T03:16:34.450 に答える
1

試してみたいかもしれません

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

WebRequestの代わりにWebClientを使用できる場合は、少し高いレベルで、ヘッダーなどの処理が簡単である必要があります。

また、このスレッドを確認することもできます: System.Net.WebClientが奇妙に失敗します

于 2012-07-24T03:04:54.343 に答える