RazorEngine WebApiTemplateBase @ Url.Content()

编程入门 行业动态 更新时间:2024-10-23 10:24:00
本文介绍了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.

推荐答案

要实现此目的的一种方法是遵循扩展模板语法,并在帮助器方法中使用 VirtualPathUtility.ToAbsolute().

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()

本文发布于:2023-11-02 08:16:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:WebApiTemplateBase   RazorEngine   Content   Url

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!