Call HTTPS REST service from WCF - wcf

I need to call some REST services from a third parties server over HTTPS. My thinking was that I would create myself a nice little WCF library to handle these calls and deserialise the responses. I'm coming a tad unstuck though.
The services I am trying to call have a test service that simply responds OK.
I have created an OperationContract in my interface as shown below:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "test")]
string Test();
In my service code I have a public method below:
public string Test()
{
ChannelFactory<IService1> factory = new ChannelFactory<IService1>("UMS");
var proxy = factory.CreateChannel();
var response = proxy.Test();
((IDisposable)proxy).Dispose();
return (string)response;
}
My app.config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<client>
<endpoint address="https://61.61.34.19/serv/ums/"
binding="webHttpBinding"
behaviorConfiguration="ums"
contract="WCFTest.IService1"
bindingConfiguration="webBinding"
name="UMS" />
</client>
<services>
<service name="WCFTest.Service1" behaviorConfiguration="WCFTest.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8731/Design_Time_Addresses/WCFTest/Service1/" />
</baseAddresses>
</host>
<endpoint address ="" binding="wsHttpBinding" contract="WCFTest.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="ums">
<clientCredentials>
<clientCertificate findValue="restapi.ext-ags.801"
storeLocation="CurrentUser"
x509FindType="FindBySubjectName"/>
</clientCredentials>
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="WCFTest.Service1Behavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="Transport">
<transport clientCredentialType="Certificate" proxyCredentialType="None"/>
</security>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
I try to invoke the test method but receive the error "Could not establish trust relationship for the SSL/TLS secure channel with authority '61.61.34.19'."
Can anyone see what I'm missing here?
Any help appreciated. Cheers.

Could not establish trust relationship for the SSL/TLS secure channel with authority '61.61.34.19'.
This typically means there's a problem with the server's SSL cert. Was it self-signed? If so, you have to establish trust for the cert, typically by trusting the issuing CA or installing the cert in the windows cert store.

Try changing the webHttpBinding security setting from "Transport" to "None".

Related

Migrating a WCF application from SOAP to REST

I have a WCF application that is currently running in SOAP configuration, and I need to convert it to REST.
In theory, I have it working, but when I call the RST API using curl, I get an error:
curl -v http://localhost:8853/ClearCore/SecMyPermissions
The message with Action '' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).
The bit where it says "Action '' cannot be processed" suggest to me that I've got the configuration wrong in such a way that it's not recognising the function name is being passed in.
C++ Code
[ServiceContract]
[Guid("5098109F-DB33-44e6-87B8-1929C879515B")]
public interface class IClearCoreSoap
{
[OperationContract]
[FaultContract(Exception::typeid)]
virtual List<System::String^>^ SecMyPermissions();
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true, ConcurrencyMode = ConcurrencyMode::Multiple,
InstanceContextMode=InstanceContextMode::PerCall,
AddressFilterMode = AddressFilterMode::Any)]
public ref class ClearCoreSoap : IClearCoreSoap
{
public:
virtual List<System::String^>^ SecMyPermissions();
}
System::ServiceModel::ServiceHost^ pServiceHost = gcnew System::ServiceModel::ServiceHost(ClearCoreSoap::typeid);
pServiceHost->Open();
WCF binding
<configuration>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding maxReceivedMessageSize="1000000" name="NoSecurity">
<readerQuotas maxDepth="1000000" maxStringContentLength="65535"/>
</binding>
<binding maxBufferSize="1000000" maxReceivedMessageSize="1000000" name="BasicSecurity">
<readerQuotas maxDepth="1000000" maxStringContentLength="65535"/>
<security mode="Transport"/>
</binding>
</webHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="webHttpBehavior" name="soapcon.ClearCoreSoap">
<endpoint address="http://localhost:8853/ClearCore" binding="webHttpBinding" bindingConfiguration="NoSecurity" contract="soapcon.IClearCoreSoap" name="ClearCore"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8853/ClearCore"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="webHttpBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/>
<serviceCredentials type="System.ServiceModel.Description.ServiceCredentials">
<clientCertificate>
<authentication certificateValidationMode="None"/>
</clientCertificate>
<userNameAuthentication customUserNamePasswordValidatorType="soapcon.ADRetry_Validator, server_console_d" userNamePasswordValidationMode="Custom"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
A "ContractFilter mismatch at the EndpointDispatcher" means the receiver could not process the message because it did not match any of the contracts the receiver has configured for the endpoint which received the message.
This can be because:
You have different contracts between client and sender.
You're using a different binding between client and sender.
The message security settings are not consistent between client and
sender.
You can refer to this thread to solve the problem.
Based on the code you provided, you can try the following:
<endpoint address="http://localhost:8853/ClearCore" binding="webHttpBinding" bindingConfiguration="NoSecurity" contract="soapcon.IClearCoreSoap" name="ClearCore"/>
Try calling http://localhost:8853/ClearCore
Add behaviour configuration in <endpoint address /> tag

Error In consuming WCF services at client side end-point not found

I am working on ASP.NET WCF simple HelloWorld Example. I have successfully completed server side but I am getting issue while working on client side. I have used SVCUTIL.exe to generate proxy classes for me.
On debug I am getting following error;
An exception of type 'System.InvalidOperationException' occurred in System.ServiceModel.dll but was not handled in user code
Additional information: Could not find endpoint element with name 'WSHttpBinding_IHelloWorldService' and contract 'IHelloWorldService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.
another thing, can I use Channel Factory if I don't access to dll file from server, say If I got access to WSDL url link
On Client Side app.config
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IHelloWorldService" />
<binding name="WSHttpBinding_IHelloWorldServiceAsyn" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8087/CreditUnionServices/HelloWorldServices/HelloWorldService"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IHelloWorldService"
contract="IHelloWorldService" name="WSHttpBinding_IHelloWorldService">
<identity>
<userPrincipalName value="DESKTOP-G6LE8I4\Khurram Zahid" />
</identity>
</endpoint>
<endpoint address="http://localhost:8087/CreditUnionServices/HelloWorldServices/HelloWorldServiceAsyn"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IHelloWorldServiceAsyn"
contract="IHelloWorldServiceAsyn" name="WSHttpBinding_IHelloWorldServiceAsyn">
<identity>
<userPrincipalName value="xyz\abc" />
</identity>
</endpoint>
</client>
</system.serviceModel>
Client Proxy Channel Factory
public class HelloWorldClient
{
public string SendTestMessage(string name)
{
ChannelFactory<IHelloWorldService> _HelloWorldClientService = new ChannelFactory<IHelloWorldService>("WSHttpBinding_IHelloWorldService");
IHelloWorldService _HelloWorldChannelService = _HelloWorldClientService.CreateChannel();
var _returnMessage = _HelloWorldChannelService.GetMessage(name);
((IClientChannel)_HelloWorldChannelService).Close();
return _returnMessage;
}
}
Server side config file
<system.serviceModel>
<services>
<service name="App.Services.Managers.HelloWorldManager" behaviorConfiguration="DefaultServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8087/CreditUnionServices/HelloWorldServices"/>
</baseAddresses>
</host>
<endpoint address="HelloWorldService" binding="wsHttpBinding" contract="App.Services.Contracts.IHelloWorldService"></endpoint>
<endpoint address="HelloWorldServiceAsyn" binding="wsHttpBinding" contract="App.Services.Contracts.IHelloWorldServiceAsyn"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultServiceBehavior">
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
Update Code
public static class HelloWorldClient
{
public static string SendTestMessage(string name)
{
HelloWorldServiceClient _helloWorldService = new HelloWorldServiceClient("WSHttpBinding_IHelloWorldService");
var _returnMessage = _helloWorldService.GetMessage("mr kz ....");
return _returnMessage;
}
}

WCF Discovery returns machine names in metadata (cannot be resolved)

So I have a WCF service hosted in IIS8 (Windows Server 2012). Here's the relevant part of the configuration file:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="MovieCorner.DAL.Service.MovieCornerDalService">
<host>
<baseAddresses>
<add baseAddress="http://192.168.221.101/MovieCorner/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding"
contract="MovieCorner.Commons.Services.IMovieCornerDalService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<endpoint kind="udpDiscoveryEndpoint" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="True" />
<serviceDiscovery />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
A simple service with a simple binding, and with a discovery endpoint. The service is up and running, everything works fine. Almost...
Here's the code I'm using on the client side (it's just a "unit" test):
var client = new DiscoveryClient(new UdpDiscoveryEndpoint());
var response = client.Find(new FindCriteria(typeof(IMovieCornerDalService)));
Assert.IsNotNull(response);
Assert.IsNotNull(response.Endpoints);
Assert.IsTrue(response.Endpoints.Count > 0);
foreach (var endpoint in response.Endpoints)
{
Console.WriteLine("Address: {0}; Contract: {1}", endpoint.Address, endpoint.ContractTypeNames[0]);
}
The code successfully finds the only running service. The output is the following:
Address: http://ws12-iis8/MovieCorner/MovieCornerDalService.svc;
Contract: http://tempuri.org/:IMovieCornerDalService
The address is returned with the machine name that hosts the service. After the discovery I want to use the service like this:
var endpoint = response.Endpoints[0];
var clientProxy = ChannelFactory<IMovieCornerDalService>.CreateChannel(new BasicHttpBinding(), endpoint.Address);
var user = clientProxy.RegisterUser("1234"); // problem
The actual method call throws an exception, and the inner exception is the following: System.Net.WebException: The remote name could not be resolved: 'ws12-iis8'
The "unit" test runs in my PC, the service is hosted in a VM. I can reach the service at the http://192.168.221.101/MovieCorner/MovieCornerDalService.svc address. But not with the machine name address.
What am I missing? What are my options? How can I retrieve the actual (private) IP of the service hosting VM? I searched for different metadata options, but I'm not a pro in the web world, so I don't know what I'm looking for.
If you need more information, let me know. Thanks for your time!

Silverlight WCF call is too large for sharepoint wcf

I have a silverlight 4 project calling a WCF service deployed on sharepoint 2010.
There are two methods a get and and a save,
teh get works fine but the save returns a generic message "Not Found"
The save is passing a large object with 2 lists. If I reduce the size of the list it all works.
So I figure I have to increase the maxReceivedMessageSize, this is easily done on the silverlight side just edit ServiceReferences.ClientConfig.
however I dont know where to do it on teh server side
Where is the binding information on the shaprepoint webserver.
I've had a look in \inetpub\wwwroot\wss\VirtualDirectories\80\web.config and it isn't there.
is there an easy way to get the binding info from teh URL?
I tried to setup some bindings for it but I just get errors
my attempt is
<bindings>
<basicHttpBinding>
<binding name="MyDemoBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyDemoBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="MyDemoBehavior" name="BEIM.Webservices.Service">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="MyDemoBinding" contract="BEIM.Webservices.IService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<host>
<baseAddresses>
<add baseAddress=”http://localhost/_vti_bin/BEIM.Webservices” />
</baseAddresses>
</host>
</service>
</services>
got the answer from here
private static void ConfigureWebService()
{
SPWebService contentService = SPWebService.ContentService;
contentService.ClientRequestServiceSettings.MaxReceivedMessageSize = -1;
SPWcfServiceSettings wcfServiceSettings = new SPWcfServiceSettings();
wcfServiceSettings.ReaderQuotasMaxStringContentLength = 10485760;
wcfServiceSettings.ReaderQuotasMaxArrayLength = 2097152;
wcfServiceSettings.ReaderQuotasMaxBytesPerRead = 10485760;
wcfServiceSettings.MaxReceivedMessageSize = 10485760;
// must be in lower case
contentService.WcfServiceSettings["service.svc"] = wcfServiceSettings;
contentService.Update();
}
I just ran it from a console app

Configuring WCF JSONP and SOAP Endpoints Listening at the same URI

I JSONP enabled my WCF ServiceContract. Client is successfully calling the JSONP Service (OperationContract). I have a number of other OperationContracts (using the same ServiceContract) that I want to expose using basicHttpBinding (SOAP) endpoint - using the same URI. I think my Service WebConfig is set up correctly. When doing such a thing, should I be able to Add the Service Reference (proxy) using the VS "Add Service Reference" dialog window? Or do I need to manually generate client code in codebehind? If I need to manually do it, can anyone provide an example? Or is my Service WebConfig not configured correctly? I am calling the JSONP Service using this: http://Flixsit:1000/FlixsitWebServices.svc/jsonp
Thanks so much...
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="DefaultBehaviors">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="JSONPBinding" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
<basicHttpBinding>
<binding name="SOAPBinding" />
</basicHttpBinding>
</bindings>
<services>
<service name="Flixsit.Services.FlixsitWebServices" behaviorConfiguration="DefaultBehaviors">
<clear />
<endpoint name="JSONPEndPoint" address="jsonp"
binding="webHttpBinding"
bindingConfiguration="JSONPBinding"
contract="Flixsit.Services.IFlixsitWebServices"
behaviorConfiguration="webHttpBehavior" />
<endpoint name="HttpEndPoint" address=""
binding="basicHttpBinding"
bindingConfiguration="SOAPBinding"
contract="Flixsit.Services.IFlixsitWebServices" />
<host>
<baseAddresses>
<add baseAddress="http://Flixsit:1000/FlixsitWebServices.svc" />
</baseAddresses>
</host>
</service>
</services>
After tooling around for a while I am creating the ChannelFactory like below (in codebehind). Services are now exposed at both endpoints.
try
{
EndpointAddress address = new EndpointAddress("http://Flixsit:1000/FlixsitWebServices.svc");
WSHttpBinding binding = new WSHttpBinding();
ChannelFactory<IFlixsitWebServices> factory = new ChannelFactory<IFlixsitWebServices>(binding, address);
IFlixsitWebServices channel = factory.CreateChannel();
//call the service operation
var customer = channel.GetCustomers();
GridView1.DataSource = customer;
GridView1.DataBind();
//close the channel
((ICommunicationObject)channel).Close();
//close factory
factory.Close();
}
catch (Exception ex)
{
//log ex;
}