C# 如何使用RazorEngine将System.Text.RegularExpressions添加到模板?

C# 如何使用RazorEngine将System.Text.RegularExpressions添加到模板?,c#,regex,razor,namespaces,razorengine,C#,Regex,Razor,Namespaces,Razorengine,我正在使用RazorEngine呈现HTML电子邮件,并希望包含帮助函数。其中一个使用正则表达式: // template.cshtml @using System.Text.RegularExpressions @functions { public string FixImageUrlParam(string url, int width, int height) { Regex widthParam = new Regex("w=[0-9]*"); Regex h

我正在使用RazorEngine呈现HTML电子邮件,并希望包含帮助函数。其中一个使用正则表达式:

// template.cshtml
@using System.Text.RegularExpressions

@functions {
  public string FixImageUrlParam(string url, int width, int height)
  {
    Regex widthParam = new Regex("w=[0-9]*");
    Regex heightParam = new Regex("h=[0-9]*");

    url = widthParam.Replace(url, $"w={width}");
    url = heightParam.Replace(url, $"h={height}");

    return url;
  }
}
这是我的配置/渲染逻辑

// renderer.cs
public static string RenderTemplate(string template, string dataModel)
{
    TemplateServiceConfiguration config = new TemplateServiceConfiguration();
    config.Namespaces.Add("System.Text.RegularExpressions");
    Engine.Razor = RazorEngineService.Create(config); ;


    Engine.Razor.AddTemplate("template", File.ReadAllText("template.cshtml"));
    Engine.Razor.Compile("template", null);
    return = Engine.Razor.Run("template", null, JsonConvert.DeserializeObject<ExpandoObject>(File.ReadAllText("data.json")));
}

您是否尝试删除字符串插值?最有可能的是,这就是错误所在

尝试将第一个代码段更改为:

// template.cshtml
@using System.Text.RegularExpressions

@functions {
  public string FixImageUrlParam(string url, int width, int height)
  {
    Regex widthParam = new Regex("w=[0-9]*");
    Regex heightParam = new Regex("h=[0-9]*");

    url = widthParam.Replace(url, "w=" + width.ToString());
    url = heightParam.Replace(url, "h=" + height.ToString());

    return url;
  }
}

什么版本的RazorEngine?我认为稳定版本默认不支持C#6,因此不能使用插值字符串。看见
// template.cshtml
@using System.Text.RegularExpressions

@functions {
  public string FixImageUrlParam(string url, int width, int height)
  {
    Regex widthParam = new Regex("w=[0-9]*");
    Regex heightParam = new Regex("h=[0-9]*");

    url = widthParam.Replace(url, "w=" + width.ToString());
    url = heightParam.Replace(url, "h=" + height.ToString());

    return url;
  }
}