1

我正在尝试动态调用需要标头身份验证的 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

我已经尝试了两种方法来传递凭据(正如您可以在代码中看到的那样),但似乎没有任何效果。

4

2 回答 2

0

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

例子 :

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

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

ClientCredentials 通过 ClientBase 类的 ClientCredentials 属性访问。

于 2013-02-18T15:00:54.907 回答
0

我还没有找到答案。我正在寻找的是在肥皂请求的标头中传递凭据。而不是以上面建议的方式使用客户端凭据

于 2013-02-25T08:53:37.900 回答