Skip to content

Instantly share code, notes, and snippets.

@malisancube
Forked from panesofglass/ViewEngineProcessor.cs
Created February 4, 2011 10:08
Show Gist options
  • Save malisancube/810947 to your computer and use it in GitHub Desktop.
Save malisancube/810947 to your computer and use it in GitHub Desktop.
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