问题描述
我正在使用ASP.NET MVC 4 Web API创建RESTful Web服务.对于API访问,我将返回JSON,尽管一旦一切正常运行,默认情况下,内容协商应适用于XML和JSON.
I am creating a RESTful Web Service using ASP.NET MVC 4 Web API. For API access, I am returning JSON, though once I get everything working correctly, the content negotiation should work for XML and JSON by default.
由于我正在努力开发真正的RESTful以资源为中心的Web服务,因此我的URI将指向实际资源.我想通过在请求中包含Accepts: text/html
时返回资源的HTML表示来利用该资源(例如在浏览器中抛出链接).
Since I am working towards a truly RESTful resource-centric web service, my URI's will be pointing to actual resources. I would like to take advantage of that by returning an HTML representation of the resource if Accepts: text/html
comes in the request (like throwing the link in a browser).
我希望能够利用MVC 4 Web API的内容协商为使用Razor模板的text/html插入渲染器.有任何可行的方法可以做到这一点吗?
I would like to be able to take advantage of MVC 4 Web API's content negotiation to insert a renderer for text/html that uses Razor templates. Are there any working examples of doing just this?
是的,这是在桥接常规" MVC页面和Web API.基本上,我想创建一个渲染器,该渲染器使用基于约定的方法来查找和渲染Razor视图,就像常规" MVC一样.我可以提出基于约定的视图查找逻辑. 我只是在寻找 a) ,将我的text/html
渲染器全局插入内容协商中,然后 b) 手动使用Razor引擎将我的模型呈现为HTML.
Yes, this is bridging "regular" MVC pages and Web API. Basically I'd like to create a renderer that uses a convention based approach to finding and rendering Razor views just like "regular" MVC. I can come up with the convention-based view lookup logic. I'm simply looking for a) globally inserting my text/html
renderer into the content negotation, and b) using the Razor engine manually to render my model into HTML.
推荐答案
FredrikNormén对此主题发表了一篇博客文章:
Fredrik Normén has a blog post on this very topic:
基本上,您需要创建一个MediaTypeFormatter
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;
}
}
}
,然后在Global.asax中注册它:
and then register it in Global.asax:
GlobalConfiguration.Configuration.Formatters.Add(new RazorFormatter());
上面的代码是从博客文章中复制的,不是我的工作
这篇关于ASP.NET MVC 4/Web API-插入用于接受的Razor渲染器:text/html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!