【问题标题】:Converting cshtml file to raw html in ASP.NET Core在 ASP.NET Core 中将 cshtml 文件转换为原始 html
【发布时间】:2022-01-24 06:40:35
【问题描述】:

我可以将 cshtml 文件转换为原始 html 文件吗?我正在寻找它,但找不到任何好的解决方案。

【问题讨论】:

  • 你想要的是the effect in this picture吗?
  • 不,我想要与 cshtml 文件完全相同的输出。
  • 像 IIS 这样的 Web 服务器就是这样做的。您不必编写任何代码。
  • 下面的回答对你有用吗?

标签: html asp.net-core razor


【解决方案1】:

几个月前在 SO 找到了这个解决方案。

public class CustomViewRendererService
{
    private readonly IRazorViewEngine _razorViewEngine;
    private readonly ITempDataProvider _tempDataProvider;

    public CustomViewRendererService(
        IRazorViewEngine razorViewEngine,
        ITempDataProvider tempDataProvider)
    {
        _razorViewEngine = razorViewEngine;
        _tempDataProvider = tempDataProvider;
    }

    public async Task<string> RenderViewToStringAsync(ControllerContext actionContext, string viewPath,
        object model)
    {
        var viewEngineResult = _razorViewEngine.GetView(viewPath, viewPath, false);

        if (viewEngineResult.View == null || (!viewEngineResult.Success))
        {
            throw new ArgumentNullException($"Unable to find view '{viewPath}'");
        }

        var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), actionContext.ModelState);
        viewDictionary.Model = model;

        var view = viewEngineResult.View;
        var tempData = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider);

        using var sw = new StringWriter();
        var viewContext =
            new ViewContext(actionContext, view, viewDictionary, tempData, sw, new HtmlHelperOptions());
        await view.RenderAsync(viewContext);
        return sw.ToString();
    }
}

使用内部控制器:

const string templatePath = "~/Views/Email/Test.cshtml";
string msg = await _viewService.RenderViewToStringAsync(ControllerContext, templatePath, new EmailConfirmationBuilderViewModel(url));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多