问题描述
|
假设我有2个本地托管的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\";
}
}
}
}
控制台应用程序可同时测试两个网站
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 \“。对于两个呼叫,服务返回失败。
解决方法
如果您要使其以这种方式工作。在单独的程序集中定义合同,并从所有三个项目中引用它。
如果再次在每个程序集中创建合同,它将使用一些默认命名。默认命名使用一些约定来定义序列化数据的名称空间,而其他名称则基于协定的.NET名称空间。因此,一旦对合同进行序列化,它将看起来像传输相同的数据,但是服务将跳过它,因为从其角度来看,数据将在错误的命名空间中定义。
编辑:
如果要将数据协定复制到多个程序集中,则必须手动定义其名称空间(3),并在所有定义上使用相同的值。