ASP.NET MVC 4 / Web API - insert Razor renderer for Accepts: text / html

I am creating a RESTful web service using ASP.NET MVC 4 web API. To return to the API, I return JSON, although as soon as I get everything that works correctly, content negotiation should work for XML and JSON by default.

Since I'm working on a truly RESTful resource oriented web service, my URI will point to the actual resources. I would like to take advantage of this by returning an HTML representation of the resource if Accepts: text/html comes in the request (for example, throws a link in the browser).

I would like to be able to use the content consistency of the MVC 4 Web API to insert a renderer for text / html using Razor templates. Are there any working examples for this?

Yes, this links the “regular” MVC pages and the web API. Basically, I would like to create a renderer that uses a convention-based approach to find and render Razor views just like a “regular” MVC. I can think of conventions based search logic. I'm just looking a) globally inserting text/html rendering into content matching and b) using the Razor mechanism manually to turn my model into HTML.

+8
asp.net-web-api razor asp.net-mvc-4 content-negotiation
source share
2 answers

Fredrik Normén has a blog post on this topic:

http://weblogs.asp.net/fredriknormen/archive/2012/06/28/using-razor-together-with-asp-net-web-api.aspx

Basically, you need to create a MediaTypeFormatter

 using System; using System.Net.Http.Formatting; namespace WebApiRazor.Models { using System.IO; using System.Net; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; using RazorEngine; public class RazorFormatter : MediaTypeFormatter { public RazorFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xhtml+xml")); } //... public override Task WriteToStreamAsync( Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext transportContext) { var task = Task.Factory.StartNew(() => { var viewPath = // Get path to the view by the name of the type var template = File.ReadAllText(viewPath); Razor.Compile(template, type, type.Name); var razor = Razor.Run(type.Name, value); var buf = System.Text.Encoding.Default.GetBytes(razor); stream.Write(buf, 0, buf.Length); stream.Flush(); }); return task; } } } 

and then register it in Global.asax:

 GlobalConfiguration.Configuration.Formatters.Add(new RazorFormatter()); 

the above code is copied from a blog post and is not my job

+3
source share

You can take a look at WebApiContrib.Formatting.Razor . This is very similar to Kyle's answer, however it is a full-blown open source project with many features, unit tests, etc. You can get it at NuGet as well.

I will say that definitely more functions are needed, but they seem to have developed it well, so it would be very easy to contribute to this.

0
source share

All Articles