How do i create a rest client with authentication in c# using channelfactory? 4.8

Viewed 12

I'm completely new to rest clients and I'm trying to create a rest client in c#. The server I'm trying to connect to requires username + password. I'm trying to add credentials to my 'channelfactory' but I'm getting this error:

"The value could not be added to the collection, as the collection already contains an item of the same type: 'System.ServiceModel.Description.ClientCredentials'. This collection only supports one instance of each type."

This is my code so far:

BasicHttpsBinding binding = new BasicHttpsBinding();
binding.Security.Mode = BasicHttpsSecurityMode.Transport;
            

ChannelFactory<ICreateChangeGP> cf = new ChannelFactory<ICreateChangeGP>(binding, "https://myurl:myport/Method1");


 ClientCredentials credentials = new ClientCredentials();
 credentials.UserName.UserName = "Username";
 credentials.UserName.Password = "Password";


 if (cf.Endpoint.Behaviors == null)
    cf.Endpoint.Behaviors.Clear();
 cf.Endpoint.Behaviors.Add(credentials);

 ICreateChangeGP channel = cf.CreateChannel();

 //a lot of backend stuff for a request

 string jsonResponse;
 var options = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented };
 string jsonInput = JsonConvert.SerializeObject(request,options);

            

 Console.WriteLine(jsonInput);
 Console.ReadLine();

 jsonResponse = channel.Method1(jsonInput);

 var response = JsonConvert.DeserializeObject<ReceiveResponse>(jsonResponse);

 Console.WriteLine(jsonResponse);

What do i need to do? Any help or pointers would be appreciated.

Best Regards

0 Answers
Related