Blog Archives
WCF REST over HTTPS
Accessing REST over HTTPS is quite a common production scenario. This would need some binding tweaks to enable transport security (highlighted in bold below). While it could be annoying for a REST purist that’s how it goes with WCF. If you are wary of modifying your configuration files for development and production among others check out this new feature available with VS 2010 which can transform web.config files during deployment.
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name=”WebHttpBindingConfig”>
<security mode=”Transport”/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name=”httpEnabled”>
<serviceMetadata httpGetEnabled=”true” httpsGetEnabled=”true” />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name=”EndpBehavior”>
<webHttp helpEnabled=”true”/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name=”Namespace.ContractImpl” behaviorConfiguration=”httpEnabled”>
<endpoint address=”" binding=”webHttpBinding” contract=”Namespace.IContract” behaviorConfiguration=”EndpBehavior” bindingConfiguration=”WebHttpBindingConfig” />
</service>
</services>
</system.serviceModel>
Creating HttpContent from a .NET Object – WCF REST Starter Kit
While I was preparing my demo for Tech Ed, I found that it isn’t quite easy to convert .NET Objects to HttpContent (provided with WCF REST Starter Kit) & Vice Versa. Additionally it requires some boilerplate code to be written every time. I thought of abstracting it out in HttpContentHelper class with 2 straight methods – CreateContentFromObject & CreateObjectFromContent. Code is given below:
public static class HttpContentHelper
{
public static HttpContent CreateContentFromObject<T>(T obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.Serialize(ms, obj);
ms.Close();
return HttpContent.Create(ms.ToArray(), “application/xml”);
return HttpContentExtensions.CreateXmlSerializable(obj); //update, see comments below
}
public static T CreateObjectFromContent<T>(HttpContent content)
{
return content.ReadAsXmlSerializable<T>();
}
}
Hope you it find it helpful
.
