从控制台应用程序ASP.NET Core 2.0渲染和访问Razor视图模板

时间:2019-03-15 21:25:08

标签: .net-core

下面是我的解决方案结构:

MyApp.Api ("call data service")
MyApp.Core ("Data Service")
MyApp.Console1.App ("Console App")
MyApp.Console2.App ("Console App")

如何从Console App中访问视图并将其呈现为字符串。

下面是MyApp.Core(“数据服务”)项目下的类。

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

当我从Controller调用它时,它可以正常工作(使用DependencyInjection)。但是我没有从Console App访问它们的方法。

我还可以从AWS S3访问我的视图吗?那会是一个可扩展的解决方案吗?

0 个答案:

没有答案