【问题标题】:How do I return HTML (the content type, not just the string) from a WebApi endpoint?如何从 WebApi 端点返回 HTML(内容类型,而不仅仅是字符串)?
【发布时间】:2015-04-18 09:37:30
【问题描述】:

这是 ASP.NET WebApi2 中的一个端点,我希望将内容类型作为 HTML 文档返回。这目前将其作为文本/纯文本返回。

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

我希望它以 text/html 的形式返回,以便在 iFrame 中正常呈现。

【问题讨论】:

  • 此时您可能只需要一个标准的 MVC 控制器。 - API 控制器应该用于返回数据,而不是 HTML。
  • 是的,通常我会从 MVC 控制器返回,但当前应用程序的方式是,这需要一个 GET 挂在同一个端点上,所以我仍然需要使用 ApiController 而不是新的MvcController
  • 看起来很可疑,为什么它需要来自同一个端点的 GET?我不确定我是否在关注你...听起来像代码味道

标签: asp.net http asp.net-web-api content-type


【解决方案1】:

您可以像这样设置ContentType

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

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

【讨论】:

  • 是的,同意。由于棕地原因,我仍然需要将其添加到现有端点。谢谢,这有效。
猜你喜欢
  • 2012-10-25
  • 1970-01-01
  • 2015-10-03
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-17
  • 1970-01-01
相关资源
最近更新 更多