WCF REST WebService 内容类型错误 [英] WCF REST WebService content type is wrong
问题描述
我使用 WCF REST 模板 40(CS) 创建了一个简单的 REST 服务,它运行良好.唯一的问题是响应使用application/json"作为内容类型,但我需要text/plain".
I created a simple REST Service using the WCF REST Template 40(CS) which is working just fine. There only is a problem that the response uses "application/json" as content type but I need "text/plain".
该问题已在博客文章中进行了解释,但由于模板的原因,我没有使用 .svc 文件.所以建议的解决方案对我不起作用.
The problem is already explained in a blog post but because of the template I'm not using a .svc file. So the proposed solution does not work for me.
我的服务合同:
[ServiceContract]
public interface ICouchService
{
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/", Method = "GET")]
ServiceInformation Hello();
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/piclib/{id}")]
CouchDocument GetDocument(string id);
}
web.config:
web.config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
推荐答案
如果要从 WCF REST 服务返回任意内容,则需要使用 Raw 编程模型 - http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx.您使用的模板使用服务路由定义了终结点,因此已为您设置好所有内容.现在您需要定义返回 Stream
参数的操作,并在操作中设置适当的内容类型:WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
If you want to return an arbitrary content from a WCF REST service, you need to use the Raw programming model - http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx. The template you used defines the endpoint using the service route, so it's all set up for you. Now you need to define the operation returning a Stream
parameter, and set the appropriate content type in the operation: WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
这篇关于WCF REST WebService 内容类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!