Create a WCF REST Client Proxy Programatically (in C#)
Posted
by Tawani
on Stack Overflow
See other posts from Stack Overflow
or by Tawani
Published on 2010-05-04T14:25:16Z
Indexed on
2010/05/04
14:28 UTC
Read the original article
Hit count: 5547
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
© Stack Overflow or respective owner