将标头参数传递给动态调用的Web服务

本文关键字:调用 Web 服务 动态 参数传递 | 更新日期: 2023-09-27 17:59:49

我正在尝试动态调用一个需要标头身份验证的Web服务但是我不知道我应该如何通过所需的头凭证

我的代码:

public object[] GeneratewebserviceProxy(string WSDL)
{
        WebRequest webRequest = WebRequest.Create(WSDL);
        System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
        ServiceDescription description = ServiceDescription.Read(requestStream);
        string sdName = description.Services[0].Name;
        string Method_Name = description.Messages["LoginSoapIn"].Name.Replace("Request", "");
        Method_Name = Method_Name.Replace("SoapIn", "");
        ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
        importer.ProtocolName = "Soap";
        importer.AddServiceDescription(description, null, null);
        CodeNamespace nmspace = new CodeNamespace();
        CodeCompileUnit unit1 = new CodeCompileUnit();
        unit1.Namespaces.Add(nmspace);
        ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
        object[] objRet = null;
        if (warning == 0)
        {
            CodeDomProvider provider1 = new CSharpCodeProvider();
            string[] assemblyReferences = new string[3]{ "System.Web.Services.dll", "System.Xml.dll", "System.Data.dll" };
            CompilerParameters parms = new CompilerParameters(assemblyReferences);
            CompilerResults results = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromDom(parms, unit1);
            object o = results.CompiledAssembly.CreateInstance(sdName);
            Type t = o.GetType();
            //PropertyInfo credentials = t.GetProperty("Credentials");
            //PropertyInfo credentials = t.GetProperty("Credentials");
           // credentials.SetValue(o, new NetworkCredential(username, passwd), null);
            MethodInfo m = t.GetMethod("Invoke", BindingFlags.NonPublic | BindingFlags.Instance);

            object[] webmethod_param = { "UserName", "Password" };
            object[] objParams = { Method_Name, webmethod_param };
            objRet = (object[])m.Invoke(o, objParams);
            if (objRet.Length > 0)
            {
                objRet = (object[])objRet[0];
            }
        }
        return objRet;
    }

请求应如下:

  tem:AuthHeader>
     <tem:Username>UserName</tem:Username>
     <tem:Password>Password</tem:Password>
  </tem:AuthHeader

我尝试了两种方式来传递凭据(正如您在代码中看到的)但似乎什么都不起作用。

将标头参数传递给动态调用的Web服务

您必须从ClientBase对象中检索ClientCredentials属性。(代码中的"o")并设置用户名和密码:

示例:

ClientCredentials.UserName.UserName = "username";
ClientCredentials.UserName.Password = "password";

来自MSDN:http://msdn.microsoft.com/it-it/library/ms599072.aspx

通过ClientBase类的ClientCredentials属性访问ClientCredential

我仍然没有找到答案。我要查找的是在soap请求的标头中传递凭据。而不是以上面建议的方式使用客户端凭据