WCF REST WebService content type is wrong

2020-04-19 05:39发布

问题:

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".

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.

My Service contract:

[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:

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

回答1:

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