C# WEB Service SOAP Header 验证


SOAP Header 定义

public class SimpleAuthorizeSoapHeader : SoapHeader
{
    public SimpleAuthorizeSoapHeader()
    {

    }

    public string Username;
    public string Password;

    //软件注册提交信息
    public string MachineCode;
    public string AuthorityNumber;
    public string ConsumerNo;

}

Web Service 定义

/// <summary>
/// SimpleAuthorizeWebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://cmono.net/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class SimpleAuthorizeWebService : System.Web.Services.WebService
{

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    public SimpleAuthorizeSoapHeader header;

    [SoapHeader("header")]
    [WebMethod(Description = "用户验证测试")]
    public string TestValidate(string content)
    {
        if (header == null)
        {
            return "您没有提及合适的参数";
        }

        if (header.Username == "changweihua" && header.Password == "123456")
        {
            SoftRegistHelper helper = new SoftRegistHelper();
            var result = helper.Regist(header.MachineCode, header.AuthorityNumber, header.ConsumerNo);

            return result;
        }


        return "您无权访问";
    }

}

客户端调用服务

object[] obj = new object[] { this.MachineCode.Text, this.Number.Text, this.Consumer.Text };
string @namespace = @"cmono.net";//命名空间
string url = URL.Text;
WebServiceHelper.InvokeWebService(url, @namespace, "Regist", obj).ToString();

WebServiceHelper

public class WebServiceHelper
{
    /// < summary> 
    /// 动态调用web服务 
    /// < /summary> 
    /// < param name="methodname">方法名< /param> 
    /// < param name="args">参数< /param> 
    /// < returns>< /returns> 
    public static object InvokeWebService(string url, string @namespace, string methodname, object[] args)
    {
        string classname = WebServiceHelper.GetWsClassName(url);
        try
        {
            //获取WSDL 
            WebClient wc = new WebClient();
            Stream stream = wc.OpenRead(url + "?WSDL");
            ServiceDescription sd = ServiceDescription.Read(stream);
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
            sdi.AddServiceDescription(sd, "", "");
            CodeNamespace cn = new CodeNamespace(@namespace);
            //生成客户端代理类代码 
            CodeCompileUnit ccu = new CodeCompileUnit();
            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            CSharpCodeProvider icc = new CSharpCodeProvider();
            //设定编译参数 
            CompilerParameters cplist = new CompilerParameters();
            cplist.GenerateExecutable = false;
            cplist.GenerateInMemory = true;
            cplist.ReferencedAssemblies.Add("System.dll");
            cplist.ReferencedAssemblies.Add("System.XML.dll");
            cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
            cplist.ReferencedAssemblies.Add("System.Data.dll");
            //编译代理类 
            CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
            if (true == cr.Errors.HasErrors)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(System.Environment.NewLine);
                }
                throw new Exception(sb.ToString());
            }

            //生成代理实例,并调用方法 
            System.Reflection.Assembly assembly = cr.CompiledAssembly;
            Type t = assembly.GetType(@namespace + "." + classname, true, true);
            object obj = Activator.CreateInstance(t);

            //给MySoapHeader赋值
            Type tt = assembly.GetType(@namespace + ".SimpleAuthorizeSoapHeader", true, true);
            object obj2 = Activator.CreateInstance(tt);

            tt.GetField("Username").SetValue(obj2, "changweihua");
            tt.GetField("Password").SetValue(obj2, "123456");

            t.GetField("SimpleAuthorizeSoapHeaderValue").SetValue(obj, obj2);

            System.Reflection.MethodInfo mi = t.GetMethod(methodname);

            return mi.Invoke(obj, args);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
        }
    }
    private static string GetWsClassName(string wsUrl)
    {
        string[] parts = wsUrl.Split('/');
        string[] pps = parts[parts.Length - 1].Split('.');
        return pps[0];
    }

}

知识共享许可协议
《C# WEB Service SOAP Header 验证》 常伟华 创作。
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议 | 3.0 中国大陆许可协议进行许可。

站内公告

A PHP Error was encountered

Severity: Core Warning

Message: PHP Startup: zip: Unable to initialize module Module compiled with module API=20060613 PHP compiled with module API=20090626 These options need to match

Filename: Unknown

Line Number: 0

Backtrace: