WCF Restful interface

For one of the projects I am working on, I needed to be able to self-host a WCF service. That in itself is a fairly simple task. It was, however, complicated by the need to allow a SilverLight 3 application on another domain access to the service. I kept getting errors relating to cross-domain permissions.

A little search on Google led me to the solution (adding the file crossdomain.xml to the root of the hosting site) but it was not the full solution. Self hosted services don’t have a site, so they don’t have a root path since there is no site.

The answer was to implement a restful interface on the service. The original posts that told me what I needed top do are here and here.

Essentially, I had to set up a new interface to allow restful communications. A stripped-down example is as follows.

using System.ServiceModel;
using System.ServiceModel.Web;
namespace TestPOCService
{
[ServiceContract]
public interface IRestfulData
{
[OperationContract, WebGet(UriTemplate = "/clientaccesspolicy.xml")]
Stream GetSilverlightPolicy();
[OperationContract, WebGet(UriTemplate = "/crossdomain.xml")]
Stream GetFlashPolicy();
}
}

The implementation included the main service interface I had defined for other purposes (and which won’t be included here) as well as the implementation of the IRestfulData interface, as follows.

using System.IO;
using System.Linq;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Xml.Linq;
namespace TestPOCService
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1, IRestfulData
{
static string CONTENT_TYPE_HTML = "text/html";
static string CONTENT_TYPE_XML = "application/xml";
static string CONTENT_TYPE_APPLICATION = "application/octet-stream";
// IService1 implementation
public Stream GetSilverlightPolicy()
{
WebOperationContext.Current.OutgoingResponse.ContentType = CONTENT_TYPE_XML;
return new MemoryStream(File.ReadAllBytes("Content/crossdomain.xml"));
}
public Stream GetFlashPolicy()
{
WebOperationContext.Current.OutgoingResponse.ContentType = CONTENT_TYPE_XML;
return new MemoryStream(File.ReadAllBytes("Content/clientaccesspolicy.xml"));
}
}
}
<div>
As you can see, This relies on the files themselves being hosted in a folder called “Content” beneath the service’s host file structure.

20110409-060908.jpg