简体   繁体   中英

Converting cshtml file to raw html in ASP.NET Core

Can I convert a cshtml file into raw html file? I'm searching for it but couldn't find any good solution.

Found this solution a few months ago at 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();
    }
}

Using inside controller:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM