我正在尝试通过 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:在传输上启用手动寻址时,必须为每个请求消息设置其目标地址。
任何人都可以帮忙吗?
干杯,安东尼。