调用webservice进行身份验证

时间:2022-11-13 14:01:40

因为同事说在调用webservice的时候会弹出身份验证的窗口,直接调用会返回401,原因是站点部署的时候设置了身份验证(账号名称自己配置)。因而在调用的时候需要加入身份验证的凭证。

调用webservice进行身份验证调用webservice进行身份验证

至于如何获取身份验证的凭据呢?可以使用微软提供的NetworkCredential(命名空间是System.Net),代码如下。

using System;
using System.Net;
using webserviceSync.helloWebservice; namespace webserviceSync
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MySoapHeader my = new MySoapHeader();
my.UserName = "";
Response.Write(webserviceClient.HelloWorld(my)); } /// <summary>
/// 获取网络凭证
/// </summary>
/// <returns></returns>
public static NetworkCredential GetCredential()
{
//return new NetworkCredential("Administrator", "888888", "192.168.2.58");//简单直接
return (NetworkCredential)CredentialCache.DefaultCredentials;//需要本地设置凭据
} /// <summary>
/// 验证凭证是否能通过
/// </summary>
/// <returns></returns>
public static bool IsVerifySucess()
{
string url = "http://192.168.2.58:7777/WebService.asmx?wsdl";
WebResponse webResponse = null;
try
{
WebRequest webRequest = WebRequest.Create(url);
webRequest.Credentials = GetCredential();
webRequest.Timeout = ;
webResponse = webRequest.GetResponse();
}
catch (Exception ex)
{ throw ex; }
return true;
} /// <summary>
/// 属性
/// </summary>
private static WebServiceSoapClient _webserviceClient = null;
/// <summary>
/// webservice服务
/// </summary>
public static WebServiceSoapClient webserviceClient
{
get
{
if (_webserviceClient == null)
{
bool isSucess = IsVerifySucess();
if (isSucess == true)
{
_webserviceClient = new WebServiceSoapClient();
_webserviceClient.ClientCredentials.Windows.ClientCredential = GetCredential();//这属性........
}
}
return _webserviceClient;
}
} }
}

如何在本地设置凭据可以参考http://jingyan.baidu.com/article/a3aad71aaa32eeb1fb0096c8.html