Webservice加上SoapHeader验证方式

提供一种基于SoapHeader的自定义验证方式,代码如下:

public class MySoapHeader : System.Web.Services.Protocols.SoapHeader
    {
        private string userID = string.Empty;
        private string userPW = string.Empty;

        public string UserId
        {
            get { return userID; }
            set { userID = value; }
        }
        public string UserPW
        {
            get { return userPW; }
            set { userPW = value; }
        }
        public MySoapHeader()
        { }
        public MySoapHeader(string name, string password)
        {
            userID = name;
            userPW = password;
        }

        private bool IsValid(string nUserId, string nPassWord, out string nMsg)
        {
            nMsg = "";
            try
            {
                if (nUserId == "admin" && nPassWord == "admin")
                {
                    return true;
                }
                else
                {
                    nMsg = "对不起,你无权调用Web服务";
                    return false;
                }
            }
            catch
            {
                nMsg = "对不起,你无权调用Web服务";
                return false;
            }
        }
        public bool IsValid(out string nMsg)
        {
            return IsValid(userID, userPW, out nMsg);
        }
    }

webservice穿插引用soapHeader:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        public MySoapHeader myheader = new MySoapHeader();
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        //该地方是调用SoapHeader地方,注意观察
        [SoapHeader("myheader")]
        [WebMethod(Description="Say Hello My World")]
        public string HelloWorld2()
        {
            string msg = "";
            if (!myheader.IsValid(out msg))
            {
                return msg;
            }            
            return "Hello World";
        }
    }    

客服端动态调用Webservice的方法,可以参考上篇博客

普通添加引用WEBSERVICE调用的方式代码如下:

 static void Main(string[] args)
        {

            MyService.WebService1SoapClient cmlent = new MyService.WebService1SoapClient();
            MyService.MySoapHeader hro=new MyService.MySoapHeader ();
            hro.UserId="admin";
            hro.UserPW="admin";
            string rsult=cmlent.HelloWorld2(hro);
            Console.WriteLine(rsult);
            Console.ReadKey();
        }
原文地址:https://www.cnblogs.com/xibei666/p/4635909.html