In my last post, I provided an overview of using the new WebGet attribute to map an HTTP GET operation to a specific method. However, I didn't cover the the necessities for hosting a service that uses this functionality.
If you intend to expose multiple endpoints that use more than one binding, it is necessary to use the traditional approach of ServiceHost. In order for WebGet to work correctly, an endpoint that uses the new binding named WebHttpBinding is required. As usual this can be done programmatically or via configuration. Regardless of the approach that is used, the WebHttpBehavior must be applied to the endpoint that is using the WebHttpBinding. This is a special endpoint behavior that enables the web programming model.
<textarea cols="50" rows="15" name="code" class="c-sharp">ServiceHost host = new ServiceHost( typeof(WeatherService), new Uri("http://localhost:8000/WeatherService")); host.AddServiceEndpoint( typeof(IWeatherService), new WebHttpBinding(), ""); host.Description.Endpoints[0].Behaviors.Add( new System.ServiceModel.Description.WebHttpBehavior()); host.Open();</textarea>
Here is the equivalent via configuration:
<textarea cols="50" rows="15" name="code" class="xhtml"><?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="WebBehavior"> <webHttp /> </behavior> </endpointBehaviors> </behaviors> <services> <service name="ServiceApplication.WeatherService"> <endpoint name="WebEndpoint" behavior="WebBehavior" address="http://localhost:8000/WeatherService" binding="webHttpBinding" contract="ServiceApplication.IWeatherService" /> </service> </services> </system.serviceModel> </configuration></textarea>
If you only intend to use the WebHttpBinding, there is a much easier alternative. There is a specialized implementation of ServiceHost named WebServiceHost that does not require any configuration. You simply specify the service type and the base uri. It will automatically use the WebHttpBinding and WebHttpBehavior.
<textarea cols="50" rows="15" name="code" class="c-sharp:nogutter">WebServiceHost host = new WebServiceHost( typeof(WeatherService), new Uri("http://localhost:8000/WeatherService")); host.Open();</textarea>
To use this host in IIS, the following .svc file could be used:
<%@
ServiceHostFactory="System.ServiceModel.Activation.WebServiceHostFactory"
Language="C#"
Service="ServiceApplication.WeatherService"
CodeBehind="~/App_Code/WeatherService.cs" %>