传递头参数以动态调用Web服务

时间:2013-02-18 14:31:39

标签: c# web-services

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

我已尝试过两种方式来传递凭据(您可以在代码中查看)  但似乎没什么用。

2 个答案:

答案 0 :(得分:0)

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

示例:

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

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

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

答案 1 :(得分:0)

我仍然没有找到答案。 我正在寻找的是在soap请求的标题中传递凭据。 而不是上面建议的客户端凭证