我正在使用ASP.NET MVC 4 Web API创建RESTful Web服务。对于API访问,我将返回JSON,尽管一旦一切正常运行,默认情况下,内容协商应适用于XML和JSON。

由于我正在努力开发真正的RESTful以资源为中心的Web服务,因此我的URI将指向实际资源。我想通过在请求中包含Accepts: text/html时返回资源的HTML表示来利用这一点(例如在浏览器中抛出链接)。

我希望能够利用MVC 4 Web API的内容协商为使用Razor模板的text/html插入渲染器。有任何可行的方法可以做到这一点吗?

是的,这桥接了“常规” MVC页面和Web API。基本上,我想创建一个渲染器,该渲染器使用基于约定的方法来查找和渲染Razor View ,就像“常规” MVC一样。我可以提出基于约定的 View 查找逻辑。 我只是在寻找 a),将我的text/html渲染器全局插入到内容协商中,而 b),使用Razor引擎手动将我的模型渲染为HTML。

最佳答案

FredrikNormé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());

上面的代码是从博客文章中复制的,不是我的工作

关于razor - ASP.NET MVC 4/Web API-插入Razor渲染器以接受: text/html,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11783094/

10-13 07:46
查看更多