WebService通過SOAP頭進行身份驗證

iDotNetSpace發表於2010-05-20

 

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt1、自定義soapheader
namespace WebService2
{
    ///


    /// Service1 的摘要說明
    ///

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    //[ToolboxItem(false)]
    // 若要允許使用 ASP.NET AJAX 從指令碼中呼叫此 Web 服務,請取消對下行的註釋。
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        public SecurityHeader currentUser;

        public Service1()
        {
            //如果使用設計的元件,請取消註釋以下行
            //InitializeComponent();
        }
        [WebMethod, SoapHeader("currentUser")]
        public string GetResult(string queryString)
        {
            if (ValidateUser(currentUser.UserName, currentUser.UserPass))
            {
                return queryString;
            }
            else
            {
                return "您不能使用該服務";
            }
        }
       //判斷邏輯
        public bool ValidateUser(string user, string pass)
        {
            if (user.Equals("user") && pass.Equals("user"))
                return true;
            else
                return false;
        }
    }
    //繼承SoapHeader
    public class SecurityHeader : System.Web.Services.Protocols.SoapHeader
    {
        public string UserName;
        public string UserPass;
    }
}
2、客戶端呼叫web服務,現將webService引用到客戶端程式
 private void button1_Click(object sender, EventArgs e)
        {
            //先定義soapheader
            Text_WebService.localhost.SecurityHeader header = new Text_WebService.localhost.SecurityHeader();

            header.UserName =textBox1.Text;
            header.UserPass =textBox2.Text;

            Text_WebService.localhost.GetResultRequest service = new Text_WebService.localhost.GetResultRequest();
            service.SecurityHeader =header;

            Text_WebService.localhost.Service1SoapClient result = new Text_WebService.localhost.Service1SoapClient();
            //result.GetResult(header, "123")
           //呼叫伺服器端的方法
            MessageBox.Show(result.GetResult(header, "123"));
        }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-663217/,如需轉載,請註明出處,否則將追究法律責任。

相關文章