Consolidating redundant declarations for a REST-full WCF service
I'm using .NET 4 WCF to expose the following REST-full webservice
[OperationContract]
[WebGet]
void Test();
Since this is a developer oriented program, I want to support REST-full HTTP developers and also developers that like to use a WSDL. My approach is to declare the service twice to expose both a traditional WSDL and also a REST endpoint:
Web.config
<serviceHostingEnvironment aspNetCompatibilityEnabled="True" multipleSiteBindingsEnabled="true" >
<serviceActivations >
<add relativeAddress ="~/KeyService.svc" service="SecretDistroMVC3.Services.KeyService3"/&g开发者_运维问答t;
</serviceActivations>
</serviceHostingEnvironment>
Global.asax
void Application_Start(object sender, EventArgs e)
{
// The following enables the WCF REST endpoint
//ASP.NET routing integration feature requires ASP.NET compatibility. Please see
// 'http://msdn.microsoft.com/en-us/library/ms731336.aspx
RouteTable.Routes.Add(new ServiceRoute("KeyService3", new WebServiceHostFactory(), typeof(KeyService3)));
Question
Since I don't like to have the service declared in two locations, how do I either configure both endpoints in config, or both endpoints in Application_Start
?
Examples
WCF's REST Help Endpoint
WCF's sample WSDL
It's probably easier doing this in the web.config file than by code. You could configure your service along the lines of the partial config shown below. I usually separate the service implementation and the WSDL & REST interface namespaces to make the config easier to understand but it is optional. The binding and behavior configuration names are there just for clarity to show how you could tweak these as needed in their respective serviceModel elements.
Since you don't want the WSDL version of the service to be affected by the ASP.NET URL routing, I set it's base address to be something like .../Wsdl/KeyService3.svc in its endpoint.
<service name="YourNamespace.Impl.KeyService3" behaviorConfiguration="yourServiceBehaviorSettings">
<!-- Service Endpoints -->
<endpoint address="Wsdl"
binding="wsHttpBinding"
bindingConfiguration="Http"
contract="YourNamespace.Wsdl.IKeyService3" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
<endpoint address="Services"
behaviorConfiguration="webBehavior"
binding="webHttpBinding"
name="webHttp"
contract="YourNamespace.IKeyService3"
listenUriMode="Explicit" />
</service>
精彩评论