Tech Tip: Setting up WCF Services in VB.Net

clive All, ASP.Net, Development, Microsoft, Tech Tip, VB.Net, WCF, Web

Windows Communication Foundation (WCF) is Microsoft’s latest generation webservice publishing technology. It’s also really badly documented; I’ve yet to find an example which says exactly what you need to do to create a WCF enabled service; plenty of examples that tell most of the story, but always missing a vital part of the jigsaw.

Here’s what you need to know (Visual Studio 2012, ASP Net 4.0, VB.Net):

Put this in the web.config file (assuming a webservice is being implemented), inside the <configuration> </configuration> tag:

<services>
<!– Note: the service name must match the configuration name for the service implementation. –>
<service name=”portal.AjaxService” behaviorConfiguration=”MyServiceTypeBehaviors”>
<endpoint contract=”IMetadataExchange” binding=”mexHttpBinding” address=”mex” />
<endpoint address=”” binding=”wsHttpBinding” contract=”portal.Service”/>
<host>
<baseAddresses>
<add baseAddress=”http://www.rectanglered.com/portal/” />
</baseAddresses>
</host>
</service>
</services>

<behaviors>
<serviceBehaviors>
<behavior name=”MyServiceTypeBehaviors” >
<serviceMetadata httpGetEnabled=”true” />
</behavior>
</serviceBehaviors>
</behaviors>

</system.serviceModel>

This assumes you have added a “AJAX Enabled WCF Service” page called ‘ajax.svc’ to your project, that your project is called ‘portal’, and the class is ‘AjaxService’, and that your webservice is to be found at ‘http://www.rectanglered.com/portal/ajax.svc’.

Here’s what your Ajax Service VB file (ajax.svc.vb) may look like:

Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web

<ServiceContract()>_
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class AjaxService

‘ To use HTTP GET, add <WebGet()> attribute. (Default ResponseFormat is WebMessageFormat.Json)
‘ To create an operation that returns XML,
‘ add <WebGet(ResponseFormat:=WebMessageFormat.Xml)>,
‘ and include the following line in the operation body:
‘ WebOperationContext.Current.OutgoingResponse.ContentType = “text/xml”
<OperationContract()> _
Public Sub DoWork()
‘ Add your operation implementation here
End Sub

End Class

… and that’s it. For information, the wsHttpBinding exposes the webservice itself to the client, and the mexHttpBinding exposes the metadata, which you will need when developing the webservice’s client to tell the client what the functions are. When deploying to production, remove the mexHttpBinding line; this will prevent unauthorised people from accessing the list of webservice functions, yet still allow your client to connect and operate properly.