Skip to content

Instantly share code, notes, and snippets.

@casper-rasmussen
Last active November 1, 2016 13:00
Show Gist options
  • Save casper-rasmussen/6db31e5e8dd78a71fe53eee6929bcf4c to your computer and use it in GitHub Desktop.
Save casper-rasmussen/6db31e5e8dd78a71fe53eee6929bcf4c to your computer and use it in GitHub Desktop.
public class GadgetApiController : ApiController
{
private readonly ITemplateResolver _templateResolver;
private readonly IContentRenderer _contentRenderer;
private readonly IContentRepository _contentRepository;
public GadgetApiController(ITemplateResolver templateResolver, IContentRenderer contentRenderer, IContentRepository contentRepository)
{
this._templateResolver = templateResolver;
this._contentRenderer = contentRenderer;
this._contentRepository = contentRepository;
}
[System.Web.Http.HttpGet]
public async Task<IHttpActionResult> Show(string contentReference)
{
//Find the content in question
IContent matchedContent = this._contentRepository.Get<IContent>(new ContentReference(contentReference));
if (matchedContent == null)
throw new ContentNotFoundException("Content was not found");
//Resolve the right Template based on Episervers own templating engine
TemplateModel model = this._templateResolver.Resolve(HttpContext.Current, matchedContent.GetOriginalType(), TemplateTypeCategories.MvcPartial | TemplateTypeCategories.MvcPartialController, new string[0]);
//Resolve the controller
ControllerBase contentController = ServiceLocator.Current.GetInstance(model.TemplateType) as ControllerBase;
//Derive the name
string controllerName = model.Name.Replace("Controller", "");
//Mimic the routing of our rendition
RouteData routeData = new RouteData();
routeData.Values.Add("currentContent", matchedContent);
routeData.Values.Add("controllerType", model.TemplateType);
routeData.Values.Add("language", ContentLanguage.PreferredCulture.Name);
routeData.Values.Add("controller", controllerName);
routeData.Values.Add("action", "Index");
routeData.Values.Add("node", matchedContent.ContentLink.ID);
//Create a fake context, that can be executed based on the route
ViewContext viewContext = new ViewContext(new ControllerContext(new HttpContextWrapper(HttpContext.Current), routeData, contentController), new FakeView(), new ViewDataDictionary(), new TempDataDictionary(), new StringWriter());
HtmlHelper helper = new HtmlHelper(viewContext, new ViewPage());
//Render in our fake context
this._contentRenderer.Render(helper, new PartialRequest(), matchedContent, model);
//Derive the output based on our template and view engine
string html = viewContext.Writer.ToString();
return Json(new { Html = html });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment