C# 读取HTTP身份验证中的领域属性

C# 读取HTTP身份验证中的领域属性,c#,httpwebrequest,basic-authentication,webresponse,C#,Httpwebrequest,Basic Authentication,Webresponse,如何读取请求HTTP基本身份验证的服务器在WWW Authenticate标头中发送的Realm属性?我假设您要创建具有基本身份验证的Web请求 如果这是正确的假设,那么您需要以下代码: // Create a request to a URL WebRequest myReq = WebRequest.Create(url); string usernamePassword = "username:password"; //Use the CredentialCache so we can a

如何读取请求HTTP基本身份验证的服务器在WWW Authenticate标头中发送的Realm属性?

我假设您要创建具有基本身份验证的Web请求

如果这是正确的假设,那么您需要以下代码:

// Create a request to a URL
WebRequest myReq = WebRequest.Create(url);
string usernamePassword = "username:password";
//Use the CredentialCache so we can attach the authentication to the request
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential("username", "password"));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
//Send and receive the response
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();

我真的不确定那些被否决的选民在这个问题上到底有什么问题

下面是获取包含基本身份验证领域的WWW Authenticate标头的粗略代码。从标题中提取实际的领域值只是一个练习,但应该非常简单(例如,使用正则表达式)


重复这个标题并没有真正的帮助。你能再详细一点吗?很清楚。我得到了我想要的帮助。谢谢,这真的很有帮助。非常感谢。这正是我需要的。我使用它来帮助确定是否要连接到Kerberos网站中托管的web服务。
public static string GetRealm(string url)
{
    var request = (HttpWebRequest)WebRequest.Create(url);
    try
    {
        using (request.GetResponse())
        {
            return null;
        }
    }
    catch (WebException e)
    {
        if (e.Response == null) return null;
        var auth = e.Response.Headers[HttpResponseHeader.WwwAuthenticate];
        if (auth == null) return null;
        // Example auth value:
        // Basic realm="Some realm"
        return ...Extract the value of "realm" here (with a regex perhaps)...
    }
}