.net core webapi 返回 html(非視圖)


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM