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

假如想象 提交于 2019-12-03 12:54:46

Fredrik Normén has a blog post on this very 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 the blog post and is not my work

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

I will say it definitely needs more features, but they seem to have designed it well so it would be very easy to contribute to it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!