在ASP.Net WebApi 中如何返回页面呢?下面的代码给出来答案
[HttpGet]
public HttpResponseMessage Report([FromBody] InspectionReportArgs args)
{
string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Reports", "CheckItem.html");
string html = File.ReadAllText(path, Encoding.UTF8);
var baseInfo = _checkItemService.GetCheckBase(args.lsh);
RenderContext renderContext = new RenderContext();
renderContext.Add(items);
renderContext.Add(baseInfo);
html = ReplaceStringVar(html, renderContext);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(html, Encoding.UTF8, "text/html")
};
return result;
}
以上的部分代码实现的是从数据库找到模块中特定值替换。
实现思路与现代替代
服务端读模板 HTML、替换占位符、以 text/html 返回,这套思路适合"复用同一模板生成报表页/邮件内容"的场景。
- MediaTypeFormatter 用 text/html,客户端浏览器直接渲染页面;
- 模板读取建议缓存(ConcurrentDictionary),避免每请求都读磁盘;
- 占位符替换可用简单 Replace 链,复杂场景上 RazorLight 之类的轻量渲染引擎;
- 纯页面展示需求,现代做法是 Razor Pages 或直接静态页 + 前端取数,WebApi 保持纯数据接口更清晰;
- 同一份 HTML 想复用为邮件正文时,注意内联样式与图片绝对地址。