WCF multiple services same contract in same Config - c#

Im trying to host to different service implementations of the same contract:
The reason is that need a dummy implementation for out-of-the-house testing.
Im trying to host both in the same WindowsService:
private ServiceHost _host;
private ServiceHost _dummy;
protected override void OnStart(string[] args)
{
_host = new ServiceHost(typeof(Service));
_host.Open();
//trying to avoid the app.config beeing used - because its already been hoste by _host
_dummy = new ServiceHost(typeof(TestDummyService));
_dummy.Description.Endpoints.Clear();
_dummy.AddServiceEndpoint(typeof(IService),
new WebHttpBinding(),
#"<link>/Dummy.svc/");
_dummy.ChannelDispatchers.Clear();
_dummy.Open();
}
This is the config file:
<system.serviceModel>
<services>
<service name="namespace.Service">
<host>
<baseAddresses>
<add baseAddress="<link>/Service.svc"/>
</baseAddresses>
</host>
<endpoint address=""
binding="webHttpBinding"
contract="namespace.IService"
behaviorConfiguration="web" />
<endpoint address="/mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors >
<behavior>
<serviceMetadata httpGetEnabled="true"
httpGetUrl="<link>/Service.svc/About" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name ="web">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
The ChannelDispatcher at /Service.svc/About with Contracts ‘IHttpGetHelpPageAndMetadataContract’ is unable to open.
any help is appreciated.
Update 1
My goal is to have 2 different implementations of the same contract (IService) hosted in one WindowsService.
I would also like to configure both of them in the config file.

Well i would like to know what's the business scenario. All I guess is, the client should not know the implementation, its just the URL of the service would indicate (or route) to the implementation.
Kindly clarify.
Refer to this existing post and let
me know if it makes sense.
The above post is hinting the implementation, refer to this post for deployment details.

so i found out, that even thow the testdummy service was added programatic, it still got the service metadatabehavior.
My solution was to not make the dehavior default - given it at name:
app.config:
<service name="namespace.Service" behaviorConfiguration="someName">
//.. later:
<behavior name="someName">
<serviceMetadata httpGetEnabled="true"
httpGetUrl="<link>/Service.svc/About" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
The rest of the code, statyed the same

Can't you add another endpoint and fill in the adress with a distinct name:
<endpoint address="/SecondService"
binding="webHttpBinding2"
contract="namespace.IService"
/>
Url becomes /Service.svc/SecondService

Related

Error in deploying WCF service on WPF application

I am working on WCF application, starting simple HelloWorld service. I have develop simple WPF application to host services, i.e. start and stop service
when I try to test this service with url "http://localhost:8087/MyServices/HelloWorldService" on WCFTestClient, I am getting following error
Error: Cannot obtain Metadata from http://localhost:8087/MyServices/HelloWorldService If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: http://localhost:8087/CreditUnionServices/HelloWorldService Metadata contains a reference that cannot be resolved: 'http://localhost:8087/CreditUnionServices/HelloWorldService'. <?xml version="1.0" encoding="utf-16"?><Fault xmlns="http://www.w3.org/2003/05/soap-envelope"><Code><Value>Sender</Value><Subcode><Value xmlns:a="http://schemas.xmlsoap.org/ws/2005/02/sc">a:BadContextToken</Value></Subcode></Code><Reason><Text xml:lang="en-GB">The message could not be processed. This is most likely because the action 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Get' is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings. The security context token would be invalid if the service aborted the channel due to inactivity. To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.</Text></Reason></Fault>HTTP GET Error URI: http://localhost:8087/CreditUnionServices/HelloWorldService There was an error downloading 'http://localhost:8087/CreditUnionServices/HelloWorldService'. The request failed with HTTP status 400: Bad Request.
app.config
<system.serviceModel>
<services>
<service name="App.Services.Managers.HelloWorldManager">
<endpoint address="HelloWorldService"
binding="wsHttpBinding"
contract="App.Services.Contracts.IHelloWorldService">
</endpoint>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8087/MyService"/>
</baseAddresses>
</host>
</service>
</services>
C# class to open and close service
public class ServicesHostManager
{
ServiceHost _helloWorldServicesHost = new ServiceHost(typeof(HelloWorldManager));
public void ProcessHelloWorldService(string _process)
{
if(!string.IsNullOrEmpty(_process))
{
try
{
if (_process.Equals("open_service"))
{
_helloWorldServicesHost.Open();
}
else if (_process.Equals("close_service"))
{
_helloWorldServicesHost.Close();
}
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.ToString());
}
}
}
The previous commenter was on the right track, you need to declare a mex endpoint. mex is what provides the MetaData.
Try the following config:
<system.serviceModel>
<services>
<service name="App.Services.Managers.HelloWorldManager" behaviorConfiguration="SimpleWcfServiceBehavior">
<endpoint address="HelloWorldService"
binding="wsHttpBinding"
contract="App.Services.Contracts.IHelloWorldService">
</endpoint>
<endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" contract="IMetadataExchange"></endpoint>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8087/MyService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SimpleWcfServiceBehavior">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
I have update code and is working now,
<system.serviceModel>
<services>
<service name="App.Services.Managers.HelloWorldManager" behaviorConfiguration="DefaultServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8087/MyService"/>
</baseAddresses>
</host>
<endpoint address="HelloWorldService" binding="wsHttpBinding" contract="App.Services.Contracts.IHelloWorldService"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultServiceBehavior">
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>

"Unable to Download Metadata" when using Two Bindings

In my book, it wants me to expose two endpoints using two bindings: WsHttpBinding & NetTCPBinding and host the service in a host application.
I use the following code in C# to try to connect to my service:
Uri BaseAddress = new Uri("http://localhost:5640/SService.svc");
Host = new ServiceHost(typeof(SServiceClient), BaseAddress);
ServiceMetadataBehavior Behaviour = new ServiceMetadataBehavior();
Behaviour.HttpGetEnabled = true;
Behaviour.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
Host.Description.Behaviors.Add(Behaviour);
Host.Open();
On the service side I have:
[ServiceContract]
public interface IService...
public class SService : IService....
Then in my Config file I have:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="WsHttpBehaviour" name="SService.SService">
<endpoint
address=""
binding="wsHttpBinding"
bindingConfiguration="WsHttpBindingConfig"
contract="SService.IService" />
<endpoint
address=""
binding="netTcpBinding"
bindingConfiguration="NetTCPBindingConfig"
contract="SService.IService" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:5640/SService.svc" />
<add baseAddress="net.tcp://localhost:5641/SService.svc" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
But when I try to add service reference to my host application, it says unable to download metadata from the address. I don't understand what is wrong and the teacher never taught this.. I decided to go ahead and look it up and learn ahead of time. I used the Editor to create the WebConfig shown above.
Can anyone point me in the right direction? I added Metadata behaviour through the editor and I set the HttpGetEnabled to true.
I can find a few issues with your code that can cause this issue:
Host = new ServiceHost(typeof(SServiceClient), BaseAddress). Pass here typeof(SService.SService) instead of typeof(SServiceClient). Change like this:
Host = new ServiceHost(typeof(SService.SService))
<service behaviorConfiguration="WsHttpBehaviour". I guess this should be "Behavior" as you have defined that. Since you have metadata enabled in config, you may remove the lines of code which add a ServiceMetadataBehavior to your servicehost.
Here is a sample that you can use for reference:
<system.serviceModel>
<services>
<service name="ConsoleApplication1.Service">
<endpoint address="" binding="wsHttpBinding" contract="ConsoleApplication1.IService" />
<endpoint address="" binding="netTcpBinding" contract="ConsoleApplication1.IService" />
<host>
<baseAddresses>
<add baseAddress="http://<machinename>:5640/SService.svc" />
<add baseAddress="net.tcp://<machinename>:5641/SService.svc" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(Service));
host.Open();
Console.ReadLine();
}
}
[ServiceContract]
public interface IService
{
[OperationContract]
string DoWork();
}
public class Service : IService
{
public string DoWork()
{
return "Hello world";
}
}
}
Metadata will be automatically available at the http baseaddress defined in the config.

Getting an error: Contract requires Duplex, but Binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it

I have a WCF service and a Silverlight 5 client.
I've defined the following interfaces:
[ServiceContract(Namespace = "Silverlight", CallbackContract = typeof(IDuplexClient))]
public interface IDuplexService
{
[OperationContract]
void Subscribe(string userId);
[OperationContract]
void Unsubscribe(string userId);
}
[ServiceContract]
public interface IDuplexClient
{
[OperationContract(IsOneWay = true)]
void PushNotification(string msg);
}
And this is my Web.config file:
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
When I try to run the service I get:
The service '/ServerService.svc' cannot be activated due to an exception during compilation. The exception message is: Contract requires Duplex, but Binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it.
I know I need to add some properties to Web.config, but wherever I looked (and whatever I tried) I couldn't make it work.
I'm new to WCF and I'd like your help on that subject. All my googling lead me nowhere and the answers people who asked here the same question got doesn't work for me.
So I've decided to give up searching and just ask.
Update: I used this link to create the interface - http://msdn.microsoft.com/en-us/library/cc645027%28v=vs.95%29.aspx
If that is the extent of your web.config configuration for WCF, then you are missing the section that defines your contract:
<services>
<service name="WebApplication1.Service1">
<endpoint address="" binding="wsDualHttpBinding" contract="WebApplication1.IService1" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
If you do have this section specified, the other likely cause is that the contract name is not fully qualified; it must include the full namespace and not just the name of the contract.
Here is the full System.ServiceModel configuration:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<service name="WebApplication1.Service1">
<endpoint address="" binding="wsHttpBinding" contract="WebApplication1.IService1" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
In this case, the application namespace is WebApplication1, the service's class name is Service1 (i.e. Service1.svc) and the interface that Service1 implements is IService1.

WCF 4 Service with REST/SOAP endpoints in IIS 7.5

Hello and thank you for reading.
I'm trying to get a service hosted in IIS 7.5, that has multiple endpoints exposed.
I have a feeling the problem lies within my web.config, but I'll post my service code in here. There's no interface file, as I'm using the newer features of WCF 4, there's also no .svc file.
All the routing, from my understanding is handled in Global.asax.cs using the RouteTable feature.
Regardless, onto the code / config -
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
// NOTE: If the service is renamed, remember to update the global.asax.cs file
public class Service1
{
// TODO: Implement the collection resource that will contain the SampleItem instances
[WebGet(UriTemplate = "HelloWorld")]
public string HelloWorld()
{
// TODO: Replace the current implementation to return a collection of SampleItem instances
return "Hello World!";
}
}
And now, the config with the changes I thought would need to be made (I'm not sure if I needed to keep the standardEndpoints block, but with or without it I'm still getting error messages. -
<services>
<service name="AiSynthDocSvc.Service1" behaviorConfiguration="HttpGetMetadata">
<endpoint name="rest"
address=""
binding="webHttpBinding"
contract="AiSynthDocSvc.Service1"
behaviorConfiguration="REST" />
<endpoint name="soap"
address="soap"
binding="basicHttpBinding"
contract="AiSynthDocSvc.Service1" />
<endpoint name="mex"
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="REST">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="HttpGetMetadata">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
The Global.asax.cs file was left alone.
Again I'm pretty sure it has something to do with my config. The error I'm getting when I try to access any of the endpoints defined is -
The endpoint at '' does not have a Binding with the None MessageVersion. 'System.ServiceModel.Description.WebHttpBehavior' is only intended for use with WebHttpBinding or similar bindings.
Anyone have any ideas on this one?
Thanks,
Zachary Carter
OK, I tried to replicate your stuff - works like a charm for me :-)
I used your service class - no changes
I used your RegisterRoutes call in global.asax.cs
When I launch the web app from within Visual Studio, I get Cassini (the built-in web server) come up on http://localhost:3131/ - this might wary in your case.
Now, I can easily navigate there with a second browser window, and I do get a simple response on this URL:
http://localhost:3131/Service1/HelloWorld
+--------------------+
from Cassini
+--------+
name (first param) in ServiceRoute registration
+-----------+
from your URI template on the WebGet attribute
Does the same URL work for you??
Update: here's my config - I can connect to http://localhost:3131/Service1/HelloWorld in the browser using REST, and I can connect to http://localhost:3131/Service1/soap with the WCF Test Client to make a SOAP call (my Service1 lives in the RestWebApp namespace - thus my service and contract names are a tad different than yours - but other than that, I believe it's identical to your own config):
<system.serviceModel>
<serviceHostingEnvironment
aspNetCompatibilityEnabled="true" />
<services>
<service name="RestWebApp.Service1" behaviorConfiguration="Meta">
<endpoint name="rest"
address=""
binding="webHttpBinding"
contract="RestWebApp.Service1"
behaviorConfiguration="REST" />
<endpoint name="SOAP"
address="soap"
binding="basicHttpBinding"
contract="RestWebApp.Service1" />
<endpoint name="mex"
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="REST">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="Meta">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
Thanks for this it helped me a lot.
The issue in my case was that I had a default behaviour configured that contains webHttp. After giving it the name="REST" and setting my webHttpBinding endpoint behaviourConfiguration ="REST" I had no further errors.
<system.serviceModel>
<bindings>
<customBinding>
<binding name="CustomBinding_IMobileService">
<binaryMessageEncoding />
<httpTransport />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="http://localhost:6862/silverlight/services/MobileService.svc"
binding="customBinding" bindingConfiguration="CustomBinding_IMobileService"
contract="AlchemyMobileService.IMobileService" name="CustomBinding_IMobileService" />
</client>
<services>
<service name="MobileService.Alchemy">
<endpoint address="http://localhost:8732/mobileservice" binding="webHttpBinding" contract="MobileService.IAlchemy" behaviorConfiguration="REST">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="REST">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>

C# WCF - Failed to invoke the service

I am getting the following error when trying to use the WCF Test Client to hit my new web service. What is weird is every once in awhile it will execute once then start popping this error.
Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.
My code (interface):
[ServiceContract(Namespace = "http://rivworks.com/Services/2010/04/19")]
public interface ISync
{
[OperationContract]
bool Execute(long ClientID);
}
My code (class):
public class Sync : ISync
{
#region ISync Members
bool ISync.Execute(long ClientID)
{
return model.Product(ClientID);
}
#endregion
}
My config (EDIT - posted entire serviceModel section):
<system.serviceModel>
<diagnostics performanceCounters="Default">
<messageLogging logMalformedMessages="true" logMessagesAtServiceLevel="true"
logMessagesAtTransportLevel="true" />
</diagnostics>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" />
<behaviors>
<endpointBehaviors>
<behavior name="JsonpServiceBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="SimpleServiceBehavior">
<serviceMetadata httpGetEnabled="True" policyVersion="Policy15"/>
</behavior>
<behavior name="RivWorks.Web.Service.ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="RivWorks.Web.Service.NegotiateService" behaviorConfiguration="SimpleServiceBehavior">
<endpoint address=""
binding="customBinding"
bindingConfiguration="jsonpBinding"
behaviorConfiguration="JsonpServiceBehavior"
contract="RivWorks.Web.Service.NegotiateService" />
<!--<host>
<baseAddresses>
<add baseAddress="http://kab.rivworks.com/services"/>
</baseAddresses>
</host>
<endpoint address=""
binding="wsHttpBinding"
contract="RivWorks.Web.Service.NegotiateService" />-->
<endpoint address="mex"
binding="mexHttpBinding"
contract="RivWorks.Web.Service.NegotiateService" />
</service>
<service name="RivWorks.Web.Service.Sync" behaviorConfiguration="RivWorks.Web.Service.ServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="RivWorks.Web.Service.ISync" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<extensions>
<bindingElementExtensions>
<add name="jsonpMessageEncoding" type="RivWorks.Web.Service.JSONPBindingExtension, RivWorks.Web.Service, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bindingElementExtensions>
</extensions>
<bindings>
<customBinding>
<binding name="jsonpBinding" >
<jsonpMessageEncoding />
<httpTransport manualAddressing="true"/>
</binding>
</customBinding>
</bindings>
</system.serviceModel>
2 questions:
What am I missing that causes this error?
How can I increase the time out for the service?
TIA!
Found the problem(s)...
Had an error inside the web service that was not handled.
The test app does not do an ABORT when it sees an error. Instead, it is left unhandled (and unreported) AND the channel is now locked because of the error.
Putting a try/catch around the inside method makes it so I can log the error and the test app does not lock up.

Categories

Resources