WCF.net动态调用Web服务方法

本文关键字:服务 方法 Web 调用 net 动态 WCF | 更新日期: 2023-09-27 17:59:16

假设我有两个本地托管的Web服务,它们都具有相同的功能。在同一个解决方案中,我有一个控制台应用程序来测试这些web服务。

//SERVICE 1
namespace Service1
{
[ServiceContract]
public interface IServiceAuthentication
{
    [OperationContract]
    string Authenticate(Authentication aut);
}

[DataContract]
public class Authentication
{
    [DataMember]
    public string username;
    [DataMember]
    public string password;
}
public class AuthenticationService : IServiceAuthentication
{
    public string Authenticate(Authentication aut)
    {
        if (aut.username == "Test1" && aut.password == "Test1")
        {
            return "passed";
        }
        else
        {
            return "failed";
        }
    }
}
}

它们的功能相同-只是不同的可信度

//SERVICE 2
namespace Service1
{
[ServiceContract]
public interface IServiceAuthentication
{
    [OperationContract]
    string Authenticate(Authentication aut);
}

[DataContract]
public class Authentication
{
    [DataMember]
    public string username;
    [DataMember]
    public string password;
}
public class AuthenticationService : IServiceAuthentication
{
    public string Authenticate(Authentication aut)
    {
        if (aut.username == "Test2" && aut.password == "Test2")
        {
            return "passed";
        }
        else
        {
            return "failed";
        }
    }
}
}

控制台应用程序测试两个Web服务

namespace WebserviceTest
{
class Program
{
    static void Main(string[] args)
    {
        WSHttpBinding wsHttpBinding = new WSHttpBinding();
        EndpointAddress endpointAddress = new EndpointAddress("http://localhost:8080/Service1/Authentication");
        IServiceAuthentication authService1 = new ChannelFactory<IServiceAuthentication>(wsHttpBinding, endpointAddress).CreateChannel();
        Console.Write(authService1.Authenticate(new Authentication() { username = "test1", password = "test1" }));
        Console.ReadKey();
        EndpointAddress endpointAddress2 = new EndpointAddress("http://localhost:8081/Service2/Authentication");
        IServiceAuthentication authService2 = new ChannelFactory<IServiceAuthentication>(wsHttpBinding, endpointAddress2).CreateChannel();
        Console.Write(authService2.Authenticate(new Authentication() { username = "test2", password = "test2" }));
        Console.ReadKey();
    }
}
[ServiceContract]
public interface IServiceAuthentication
{
    [OperationContract]
    string Authenticate(Authentication aut);
}

[DataContract]
public class Authentication
{
    [DataMember]
    public string username;
    [DataMember]
    public string password;
}
}

我遇到的问题是,这些方法是从web服务端正确执行的,但对象参数Authentication为null-尽管我正在传递"test1",test1和"test2",test2。对于这两个调用,显然服务返回失败。

WCF.net动态调用Web服务方法

如果你想让它以这种方式工作。在单独的程序集中定义合同,并从所有三个项目中引用它。

如果您在每个程序集中再次创建约定,它将使用一些默认命名。默认命名使用一些约定来定义序列化数据的名称空间,它基于协定的.NET名称空间。因此,一旦契约被序列化,它看起来就像传输相同的数据,但服务会跳过它,因为从它的角度来看,数据将在错误的命名空间中定义。

编辑:

如果要将中的数据协定复制到多个程序集,则必须手动定义其命名空间[DataContract(Namespace = "SomeUri")],并在所有定义中使用相同的值。