我有一个包含文件夹视图/表单的 MVC Web API 项目,我想将视图读取为 HTML 字符串,包括部分视图;
这是我从视图中获取 HTML 字符串的代码
public class HtmlActionResult : IHttpActionResult
{
private const string ViewDirectory = @"..\Views\Forms";
private readonly string _view;
private readonly dynamic _model;
public HtmlActionResult(string viewName, dynamic model)
{
_view = LoadView(viewName);
_model = model;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
var parsedView = RazorEngine.Razor.Parse(_view, _model);
response.Content = new StringContent(parsedView);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return Task.FromResult(response);
}
private static string LoadView(string name)
{
string path = HttpContext.Current.Server.MapPath("~/views/forms");
path = Path.Combine(path, name + ".cshtml");
string view = string.Empty;
if (File.Exists(path))
view = File.ReadAllText(path);
return view;
}
这是它的执行方式:
var htmlAction = new HtmlActionResult("MyView", MyModel);
var response = await htmlAction.ExecuteAsync(new CancellationToken());
MyView 在同一个文件夹(视图/表单)中包含一个局部视图,称为separator.cshtml
如何渲染部分视图separator.cshtml
,我尝试添加参考解析器,如下所述:
并在获取 HTML 响应字符串之前添加了以下代码:
var config = new TemplateServiceConfiguration();
config.ReferenceResolver = new MyIReferenceResolver();
var service = RazorEngineService.Create(config);