我正在尝试通过MonoTouch访问WCF REST服务。我无法使用ChannelFactory,因为在MonoTouch中无法生成动态代码,并且因为我正在访问RESTful服务,所以我也无法使用svcutil来构建客户端类。
这让我手动构建客户端类。我已经走得很远但遇到了问题,这是代理类的代码:
public class AuthenticationClient : System.ServiceModel.ClientBase<IAuthenticationService>, IAuthenticationService
{
public AuthenticationClient(Binding binding, EndpointAddress baseAddress) : base(binding, baseAddress)
{ }
public AuthenticationResult AuthenticateUser (AccountCredentials credentials)
{
return base.Channel.AuthenticateUser(credentials);
}
protected override IAuthenticationService CreateChannel ()
{
// This method must be overriden in MonoTouch to prevent using a ChannelFactory
return new AuthenticationChannel(this);
}
private class AuthenticationChannel : ChannelBase<IAuthenticationService>, IAuthenticationService
{
public AuthenticationChannel(System.ServiceModel.ClientBase<IAuthenticationService> client) :
base(client)
{ }
public AuthenticationResult AuthenticateUser (AccountCredentials credentials)
{
object[] _args = new object[1];
_args[0] = credentials;
return (AuthenticationResult)base.Invoke("AuthenticateUser", _args); // Exception thrown here
}
}
}
接口IAuthenticationService使用属性来指定端点Uri:
[ServiceContract]
public interface IAuthenticationService
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/Authenticate/User")]
AuthenticationResult AuthenticateUser(AccountCredentials credentials);
}
以下是我使用代理类的方法:
var serviceHost = "http://mydomain.com/";
var servicePath = "Services/Authentication";
Uri hostUri = new Uri(serviceHost);
Uri serviceUri = new Uri(hostUri, servicePath);
var binding = new WebHttpBinding();
var client = new AuthenticationClient(binding, new EndpointAddress(serviceUri));
client.Endpoint.Behaviors.Add(new MyWebHttpBehaviour());
var credentials = new AccountCredentials
{
Username = "myusername",
Password = "mypassword"
};
var result = client.AuthenticateUser(credentials);
(由于某种原因,WebHttpBehavior没有实现IEndpointBehavior,所以我创建了自己的类,它继承自WebHttpBehavior并实现了IEndpointBehavior)。
我收到的例外是:
System.InvalidOperationException:在传输上启用手动寻址时,必须为每个请求消息设置其目标地址。
有人可以帮忙吗?
干杯, 安东尼。