因為同事說在調用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)); } /// <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 = 15000; 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