【问题标题】:Display the contents of the file to the browser instead of downloading it将文件的内容显示到浏览器而不是下载它
【发布时间】:2015-10-08 10:15:00
【问题描述】:

我正在尝试构建一个简单的 RESTful 应用程序。我有 WFC 服务。

在界面中我有下一个方法:

[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "get")]
Stream GetPage();

并实现这个方法:

public System.IO.Stream GetPage()
{
    MemoryStream ms = new MemoryStream();
    StreamWriter sw = new StreamWriter(ms);
    sw.WriteLine("HTTP/1.0 200 OK");
    sw.WriteLine("Content-Type: text/html");
    sw.Write(Properties.Resources.page);
    sw.Flush();
    ms.Position = 0;
    return ms;
}

资源页面:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
    Hello word!!!
</body>
</html>

但是当我转到localhost/MyService/Get 时,浏览器会下载文件而不是显示它。

如何在浏览器中显示此内容?

【问题讨论】:

  • 您是在尝试创建 RESTful 应用程序/服务,还是 Web 服务器?
  • RESTful 服务。我了解我的服务运行正常。现在我需要在客户端显示结果。
  • 您的客户端是网络浏览器吗(与网络服务器通信,并期望 HTTP 响应)?
  • 为什么要从 REST 服务返回 HTML?为什么使用 WCF 而不是 WebAPI?
  • @Amit,是的,客户端是网络浏览器。我想在浏览器中显示内容。我使用 Fiddler 来查看我得到的响应。服务器返回Content-Type: application/octet-stream.. 但是为什么呢?

标签: c# .net wcf rest


【解决方案1】:

即使您通过让"raw" WCF REST response method 返回Stream 来创建"raw" WCF REST response method,您仍然只能控制使用该流的HTTP 消息的响应正文。

因此,您写入返回的流中的 HTTP 标头将被视为内容,而不是接收者的标头。

您需要按照WCF REST: specify content-type on WebGet Attribute doesn't seem to be working 中的说明显式设置标头:

WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";

【讨论】:

    猜你喜欢
    • 2014-07-16
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    相关资源
    最近更新 更多