因为同事说在调用webservice的时候会弹出身份验证的窗口,直接调用会返回401,原因是站点部署的时候设置了身份验证(账号名称自己配置)。因而在调用的时候需要加入身份验证的凭证。
至于如何获取身份验证的凭据呢?可以使用微软提供的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)); } ////// 获取网络凭证 /// ///public static NetworkCredential GetCredential() { //return new NetworkCredential("Administrator", "888888", "192.168.2.58");//简单直接 return (NetworkCredential)CredentialCache.DefaultCredentials;//需要本地设置凭据 } /// /// 验证凭证是否能通过 /// ///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 = 15000; webResponse = webRequest.GetResponse(); } catch (Exception ex) { throw ex; } return true; } /// /// 属性 /// private static WebServiceSoapClient _webserviceClient = null; ////// webservice服务 /// public static WebServiceSoapClient webserviceClient { get { if (_webserviceClient == null) { bool isSucess = IsVerifySucess(); if (isSucess == true) { _webserviceClient = new WebServiceSoapClient(); _webserviceClient.ClientCredentials.Windows.ClientCredential = GetCredential();//这属性........ } } return _webserviceClient; } } }}
如何在本地设置凭据可以参考