RazorEngine WebApiTemplateBase @ Url.Content() [英] RazorEngine WebApiTemplateBase @Url.Content()

查看:48
本文介绍了RazorEngine WebApiTemplateBase @ Url.Content()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从ASP.NET Web API使用RazorEngine时,如何在 _Layout.cshtml 中使 @ Url.Content()工作?

How can I get @Url.Content() working in my _Layout.cshtml when RazorEngine is being used from ASP.NET Web API?

RazorEngine (v.3.7.2)仅处理Razor语法,而不处理其他帮助程序方法,例如 @Html @Url .这些可以通过扩展 TemplateBase<> 并将其设置在配置中来添加.

RazorEngine (v.3.7.2) only deals with the Razor syntax and not the additional helper methods like @Html or @Url. These can be added by extending the TemplateBase<> and setting it in the configuration.

在一些旧问题中有代码示例:#26 #29 ;在中未发布的,不完整的代码中MvcTemplateBase.cs ;以及扩展模板语法的文档中.

There are code examples in some old issues: #26, #29; in an unreleased, incomplete piece of code in MvcTemplateBase.cs; and in the documentation for Extending the Template Syntax.

我的问题是我正在使用没有 HttpContext.Current (也不应该)的ASP.NET Web API(v.1).我想提供一个 UrlHelper ,因为我想使用它的 Content()方法,但是需要使用 HttpRequestMessage 实例化它,可用.

My problem is I'm using ASP.NET Web API (v.1) which won't have HttpContext.Current (nor should it). I want to provide a UrlHelper as I want to use its Content() method but it needs to be instantiated with the HttpRequestMessage which won't be available.

也许没有办法为我的已编译布局获取@Url帮助器方法.也许我需要从虚拟路径获取绝对路径的其他方法.似乎我仍然需要一些方法来检查请求.

Perhaps there's no way to get @Url helper methods for my compiled layout. Perhaps I need some other way of getting the absolute path from the virtual path. It seems I'd still need some way of checking the Request though.

推荐答案

要实现此目的的一种方法是遵循

A way to get this working is to follow the direction set by Extending the Template Syntax and use VirtualPathUtility.ToAbsolute() in a helper method.

using System.Web;
using RazorEngine.Templating;

namespace MyNamespace.Web
{
    public abstract class WebApiTemplateBase<T> : TemplateBase<T>
    {
        protected WebApiTemplateBase()
        {
            Url = new UrlHelper();
        }

        public UrlHelper Url;
    }

    public class UrlHelper
    {
        public string Content(string content)
        {
            return VirtualPathUtility.ToAbsolute(content);
        }
    }
}

使用 TemplateBase<> 的此扩展名设置TemplateService配置.

Set up the TemplateService configuration with this extension of the TemplateBase<>.

var config =
    new RazorEngine.Configuration.TemplateServiceConfiguration
    {
        TemplateManager = new TemplateManager(),
        BaseTemplateType = typeof(WebApiTemplateBase<>)
    };

这篇关于RazorEngine WebApiTemplateBase @ Url.Content()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆