我找到了一些关于如何在ASP.NET中将视图返回到字符串的文章,但无法转换成能够在.NET Core中运行的文章

public static string RenderViewToString(this Controller controller, string viewName, object model)
{
    var context = controller.ControllerContext;
    if (string.IsNullOrEmpty(viewName))
        viewName = context.RouteData.GetRequiredString("action");

    var viewData = new ViewDataDictionary(model);

    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
        var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

假设能够通过以下方式从控制器调用:

var strView = this.RenderViewToString("YourViewName", yourModel);

当我试着把上面提到的.NET Core我有很多编译错误.

我试着把它改成和你一起工作.NET核心,但失败了,谁能帮我提一下project.json中需要使用的using .."dependencies": { "Microsoft.AspNetCore.Mvc": "1.1.0", ... },.

其他一些示例代码是hereherehere

NOTE 我需要在.NET Core中将视图转换为string的解决方案,无论转换的代码是相同的,还是可以通过其他方式转换的.

推荐答案

多亏了Paris Polyzos和他的article.

我在这里重新张贴他的代码,以防原来的帖子因为任何原因被删除.

在文件viewToString.cs中创建Service,代码如下:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
     
namespace WebApplication.Services
{
        public interface IViewRenderService
        {
            Task<string> RenderToStringAsync(string viewName, object model);
        }
     
        public class ViewRenderService : IViewRenderService
        {
            private readonly IRazorViewEngine _razorViewEngine;
            private readonly ITempDataProvider _tempDataProvider;
            private readonly IServiceProvider _serviceProvider;
     
            public ViewRenderService(IRazorViewEngine razorViewEngine,
                ITempDataProvider tempDataProvider,
                IServiceProvider serviceProvider)
            {
                _razorViewEngine = razorViewEngine;
                _tempDataProvider = tempDataProvider;
                _serviceProvider = serviceProvider;
            }
     
            public async Task<string> RenderToStringAsync(string viewName, object model)
            {
                var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
                var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
     
                using (var sw = new StringWriter())
                {
                    var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);
     
                    if (viewResult.View == null)
                    {
                        throw new ArgumentNullException($"{viewName} does not match any available view");
                    }
     
                    var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                    {
                        Model = model
                    };
     
                    var viewContext = new ViewContext(
                        actionContext,
                        viewResult.View,
                        viewDictionary,
                        new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                        sw,
                        new HtmlHelperOptions()
                    );
     
                    await viewResult.View.RenderAsync(viewContext);
                    return sw.ToString();
                }
            }
        }
}

2.将服务添加到Startup.cs文件,如下所示:

using WebApplication.Services;

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddScoped<IViewRenderService, ViewRenderService>();
}

3."preserveCompilationContext": true添加到project.json中的buildOptions,使文件看起来像:

{
    "version": "1.0.0-*",
    "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true,
    "preserveCompilationContext": true
    },
    "dependencies": {
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.Mvc": "1.0.1"
    },
    "frameworks": {
    "netcoreapp1.0": {
        "dependencies": {
        "Microsoft.NETCore.App": {
            "type": "platform",
            "version": "1.0.1"
        }
        },
        "imports": "dnxcore50"
    }
    }
}

4.定义你model,例如:

public class InviteViewModel {
    public string   UserId {get; set;}
    public string   UserName {get; set;}
    public string   ReferralCode {get; set;}
    public int  Credits {get; set;}
}

5.创建您的Invite.cshtml,例如:

@{
    ViewData["Title"] = "Contact";
}
@ViewData["Title"].
user id: @Model.UserId

Controller人中的6.人:

a..在开头定义以下内容:

private readonly IViewRenderService _viewRenderService;

public RenderController(IViewRenderService viewRenderService)
{
    _viewRenderService = viewRenderService;
}

b.调用并返回模型视图,如下所示:

var result = await _viewRenderService.RenderToStringAsync("Email/Invite", viewModel);
return Content(result);

c.完整的控制器示例可能如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication.Services;

namespace WebApplication.Controllers
{
    [Route("render")]
    public class RenderController : Controller
    {
        private readonly IViewRenderService _viewRenderService;

        public RenderController(IViewRenderService viewRenderService)
        {
            _viewRenderService = viewRenderService;
        }

    [Route("invite")]
    public async Task<IActionResult> RenderInviteView()
    {
        ViewData["Message"] = "Your application description page.";
        var viewModel = new InviteViewModel
        {
            UserId = "cdb86aea-e3d6-4fdd-9b7f-55e12b710f78",
            UserName = "Hasan",
            ReferralCode = "55e12b710f78",
            Credits = 10
        };
     
        var result = await _viewRenderService.RenderToStringAsync("Email/Invite", viewModel);
        return Content(result);
    }

    public class InviteViewModel {
        public string   UserId {get; set;}
        public string   UserName {get; set;}
        public string   ReferralCode {get; set;}
        public int  Credits {get; set;}
    } 
}

Asp.net相关问答推荐

SameSite 属性如何自动添加到我的 Asp.net_SessionID cookie 中?

Ef core:执行 MaxAsync 时序列不包含任何元素

Httpclient 该实例已经启动了一个或多个请求.只能在发送第一个请求之前修改属性

只接受波斯字符的正则表达式

如何在 Asp.net core 2.0 中使用 log4net

如何在 C#/MVC 4 中的 Html.TextBoxFor 中输入占位符文本

如何在 ASP.NET Core 中更改 Swagger 的基本 url

如何在 .NET Core 中实现 DbContext 连接字符串?

返回 JSON 对象 (ASP.NET WebAPI)

客户端和服务器无法通信,因为它们没有通用算法 - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

ASP.NET 核心,更改未经授权的默认重定向

RestSharp 获取请求的完整 URL

从 Web API 使用 HttpClient 发布 JsonObject

在 aspnetcore (netcoreapp1.0) 中替代 System.Web.Security.Membership.GeneratePassword

找不到与目标运行时之一兼容的框架 .NETCoreApp=v1 的运行时目标

在 ASP.NET Core 中读取环境变量

解析 JSON 响应的最简单方法

Task.Run 在 ASP .NET MVC Web 应用程序中被认为是不好的做法吗?

使用实体框架从存储过程中获取数据

IIS 中的 existingResponse="PassThrough" 是什么意思?