0

I am trying to create a REST Client proxy programatically in C# using the code below but I keep getting a CommunicationException error. Am I missing something?

public static class WebProxyFactory
{
    public static T Create<T>(string url) where T : class
    {
        ServicePointManager.Expect100Continue = false;
        WebHttpBinding binding = new WebHttpBinding();

        binding.MaxReceivedMessageSize = 1000000;

        WebChannelFactory<T> factory =
          new WebChannelFactory<T>(binding, new Uri(url));

        T proxy = factory.CreateChannel();

        return proxy;
    }

    public static T Create<T>(string url, string userName, string password)
      where T : class
    {
        ServicePointManager.Expect100Continue = false;
        WebHttpBinding binding = new WebHttpBinding();

        binding.Security.Mode =
          WebHttpSecurityMode.TransportCredentialOnly;
        binding.Security.Transport.ClientCredentialType =
          HttpClientCredentialType.Basic;
        binding.UseDefaultWebProxy = false;

        binding.MaxReceivedMessageSize = 1000000;

        WebChannelFactory<T> factory =
          new WebChannelFactory<T>(binding, new Uri(url));

        ClientCredentials credentials = factory.Credentials;
        credentials.UserName.UserName = userName;
        credentials.UserName.Password = password;

        T proxy = factory.CreateChannel();

        return proxy;
    }
}

So that I can use it as follows:

IMyRestService proxy = WebProxyFactory.Create<IMyRestService>(url, usr, pwd);
var result = proxy.GetSomthing(); // Fails right here
Tawani
  • 11,067
  • 20
  • 82
  • 106
  • 1
    i don't yet understand why, but in another question the issue was adding the webhttpbinding to the factory endpoint behaviors: factory.Endpoint.Behaviors.Add(new WebHttpBehavior()); – James Manning Jul 04 '10 at 15:50
  • THat didn't work either. Any other suggestions? – Tawani Jul 07 '10 at 20:17

1 Answers1

0

For this to work with Forms Authentication, I had to physically override the Authentication headers as follows:

var proxy = WebProxyFactory.Create<ITitleWorldService>(url, userName, password);

using (new OperationContextScope((IContextChannel)proxy))
{
    var authorizationToken = GetBasicAuthorizationToken(userName, password);
    var httpRequestProperty = new HttpRequestMessageProperty();
    httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = authorizationToken;
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

    //var response = proxy.DoWork();    
    Console.WriteLine(proxy.SayHello());
}
Tawani
  • 11,067
  • 20
  • 82
  • 106