测试访问网页的凭据

问题描述 投票:0回答:2

有没有一段不错且经过测试的代码可以用于此目的:

获取用户/通行证和Web服务的地址(asmx页面)并检查用户/通行证是否有效。

我认为我应该使用 HTTPRequest 等来做到这一点,但我对该主题没有很好的了解,导致我当前的方法无法正常工作。

如果有一段很好的代码用于此目的,我很感激您向我指出这一点。

谢谢

P.S:我没有在代码中使用 DefaultCredentials。因为我希望他们输入用户/通行证,所以现在我需要能够测试他们的用户/通行证,并在他们的凭据无效时向他们显示正确的消息。

c# asmx xmlhttprequest credentials
2个回答
1
投票

您可以使用 HttpWebRequest.Credentials Property(取决于 Web 服务身份验证)和 CredentialCache Class

还有一些代码示例(来自谷歌):
在 .NET 中检索 HTTP 内容
使用 HttpWebRequest 动态调用 Web 服务

.Credentials
结合起来。


1
投票
public bool TestCredentials(string url, string username, string password)
{
    var web = new WebClient();
    web.Credentials = new NetworkCredential(username,password);

    try
    {   
        web.DownloadData(url);
        return true;
    }
    catch (WebException ex)
    {
        var response = (HttpWebResponse)ex.Response;
        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            return false;
        }

        throw;
    }   
}
© www.soinside.com 2019 - 2024. All rights reserved.