如何从 WebApi 端点 return HTML (内容类型,而不仅仅是字符串)?

How do I return HTML (the content type, not just the string) from a WebApi endpoint?

这是 ASP.NET WebApi2 中的一个端点,我希望将内容类型 return 编辑为 HTML 文档。目前 return 为 text/plain。

 public HttpResponseMessage GetHtmlPreview(int id, bool isHtml)
    {
        var msg = new HttpResponseMessage()
        {
            Content = new StringContent("<html><head><title>test</title></head><body><h2>TEST HTML STUFF HERE" + id + "</h2></body>"),
        };
        return msg;
    }

我希望它 return 与 text/html 一样,以便它在 iFrame 中呈现良好。

您可以这样设置 ContentType

msg.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");

我同意 BenjaminPaul 的观点,由你的控制器支持的视图在这里似乎是更好的方法。