Fredrik Normén 有一篇关于这个主题的博文:
http://weblogs.asp.net/fredriknormen/archive/2012/06/28/using-razor-together-with-asp-net-web-api.aspx
基本上,您需要创建一个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;
}
}
}
然后在 Global.asax 中注册:
GlobalConfiguration.Configuration.Formatters.Add(new RazorFormatter());
上面的代码是从博客文章中复制的,不是我的工作