.net core webapi 返回 html(非视图)
近期遇到很多提示的问题,所以很多时候,需要后端返回html到前端作为提示。那么很多时候,可以在后端控制,就要用到这种方法:
使用dotnet core webpi的时候,如何返回html格式到前端。
使用语言:C#
当前环境:.Net Core 2.2.6(SDK)version:2.2.401
废话不多说,直接上代码(最后的代码块就是我们的完整代码)
核心代码:
public async Task ReturnHtml() { StringBuilder htmlStringBuilder = new StringBuilder(); var data = Encoding.UTF8.GetBytes("返回的内容"); if (accept.Any(x => x.MediaType == "text/html")) { Response.ContentType = "text/html"; } else { Response.ContentType = "text/plain"; } await Response.Body.WriteAsync(data, 0, data.Length); }
完整代码:
/// <summary> /// 返回html的组合 /// </summary> /// <returns></returns> [HttpGet] [Route("api/Message/ReturnHtml")] public async Task ReturnHtml() { StringBuilder htmlStringBuilder = new StringBuilder(); htmlStringBuilder.Append("<html>"); htmlStringBuilder.Append("<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head>");//支持中文 htmlStringBuilder.Append("<body>"); htmlStringBuilder.Append("<spen style="font-size: 300%">");//让字体变大 string a = $"返回的内容"; htmlStringBuilder.Append(a); htmlStringBuilder.Append("</spen>"); htmlStringBuilder.Append("</body>"); htmlStringBuilder.Append("</html>"); result = htmlStringBuilder.ToString(); var data = Encoding.UTF8.GetBytes(result); if (accept.Any(x => x.MediaType == "text/html")) { Response.ContentType = "text/html"; } else { Response.ContentType = "text/plain"; } await Response.Body.WriteAsync(data, 0, data.Length); }