Skip to content

Instantly share code, notes, and snippets.

@panesofglass
Created February 4, 2011 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save panesofglass/810805 to your computer and use it in GitHub Desktop.
Save panesofglass/810805 to your computer and use it in GitHub Desktop.
A view engine media type formatter for WCF Web APIs
using System;
using System.Collections.Generic;
using System.ServiceModel.Description;
using Microsoft.ServiceModel.Http;
using Nina.ViewEngines;
namespace Http.Formatters
{
public class ViewEngineProcessor<T> : GenericMediaTypeProcessor<T>
{
private static readonly IDictionary<string, ITemplate> _cache = new Dictionary<string, ITemplate>();
private readonly string _basePath;
public ViewEngineProcessor(HttpOperationDescription operation, MediaTypeProcessorMode mode, string basePath = "Views/")
: base(operation, mode)
{
_basePath = basePath;
}
public override IEnumerable<string> SupportedMediaTypes
{
get
{
yield return "text/html";
//yield return "application/xhtml+xml";
}
}
public override object ReadFromStream(System.IO.Stream stream, System.Net.Http.HttpRequestMessage request)
{
throw new NotImplementedException();
}
public override void WriteToStream(T instance, System.IO.Stream stream, System.Net.Http.HttpRequestMessage request)
{
ITemplate template;
string templateName = _basePath + typeof(T).Name;
Type modelType = instance.GetType();
if (Nina.Configuration.Configure.IsDevelopment || !_cache.TryGetValue(templateName, out template))
{
template = Nina.Configuration.Configure.Views.Engine.Compile<T>(templateName);
_cache[templateName] = template;
}
using (var sw = new System.IO.StreamWriter(stream.PreventClose()))
{
template.Render(sw, instance);
sw.Flush();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment