I am working on a plug-in architecture for “widgets” on a website. I would like each individual widget to store its Javascript and CSS as resources in the assembly. When the page is rendered, I inject script tags that reference a WCF service that can inspect the widget, extract the desired file, and send it back to the browser.
This is working fine for the Javascript files, but the browser can’t handle the CSS file coming through as an octet stream. Normally, you can just change the content type of the response in HttpContext, but that’s not available in a WCF service.
What I need is to have the browser retrieve these files through a url like so:
<link type="text/css" rel="stylesheet" href="/Controllers/WidgetFileService.svc/style/WidgetId">
I would prefer not to implement a custom IHttpHandler, because, in my experience, those can be difficult to deploy, debug, and get working on different machines. This is my first project at this company and I would rather not complicate deployment and testing.
Here is what I have for the interface:
[ServiceContract]
public interface IWidgetFileService
{
[OperationContract]
[WebGet(UriTemplate = "style/{widgetID}", BodyStyle = WebMessageBodyStyle.Bare)]
System.IO.Stream GetStyleFile(String widgetID);
}
And the implementation:
static private System.IO.Stream StreamBytes(byte[] data)
{
System.IO.Stream s = new System.IO.MemoryStream(data);
s.Position = 0;
return s;
}
public System.IO.Stream GetStyleFile(String widgetID)
{
IWidget w = GetWidget(widgetID);
return StreamBytes(w.GetEditorStyleFile());
}
If I browse to the URL, the data comes back as expected. It seems to be the way the browser is handling the request that is causing the issue.
You can use the WebOperationContext to get access to the outgoing response in a WCF service. I’ve verified this sends it to the browser with the specified content type.