WCF 4.0 Rest Service返回内容类型text / html

时间:2011-11-16 06:50:30

标签: .net wcf

我有一个WCF 4.0 REST服务。如果我在automaticFormatSelectionEnabled文件中启用web.config,则服务将在基于HTTP"接受"序列化为XML或JSON之间正确选择。报头中。

但是,当我使用浏览器发出GET命令时,响应正文将返回格式化为XML,但HTTP内容类型标题为" text / html"。这导致浏览器没有意识到响应是XML并尝试将其呈现为html(这当然不能很好地工作)。这使得在浏览器中测试我的GET方法变得更加困难。

如果我禁用automaticFormatSelectionEnabled,那么一切都按预期工作(响应正文包含XML,HTTP内容类型是" application / xml")但是,我想成为能够在请求时自动切换到JSON。

通过浏览器请求时,是否有某种方法可以使内容类型正确返回?

1 个答案:

答案 0 :(得分:3)

我遇到了同样的问题,这是一个解决方法。基本上你需要做的是创建一个行为扩展,它将在发送响应时改变内容类型。

您的web.config需要包含以下内容:

<behaviors>
  <serviceBehaviors>
    <behavior name="WebServiceBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
      <MessageInspector/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<extensions>
  <behaviorExtensions>
    <add name="MessageInspector"
          type="Namespace.ServiceContentTypeBehaviorExtensionElement, assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
  </behaviorExtensions>
</extensions>

然后,您需要创建一个继承自BehaviorExtensionElement

的类
public class ServiceContentTypeBehaviorExtensionElement : BehaviorExtensionElement
{
    protected override object CreateBehavior()
    {
        return new ServiceContentTypeMessageInspector();
    }

    public override Type BehaviorType
    {
        get
        {
            return typeof(ServiceContentTypeMessageInspector);
        }
    }
}

最后是一个实现IDispatchMessageInspector和IServiceBehavior的类,它完成了改变内容类型的艰苦工作:

public class ServiceContentTypeMessageInspector : IDispatchMessageInspector, IServiceBehavior
{

    #region IDispatchMessageInspector

    public object AfterReceiveRequest(ref Message request, IClientChannel channel,
        InstanceContext instanceContext)
    {
        return null;
    }

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        // inspect and/or modify the reply
        if (WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.ContentType] == "text/html; charset=utf-8" &&
            WebOperationContext.Current.OutgoingResponse.Format == WebMessageFormat.Xml)
        {
            WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.ContentType] = "application/xml; charset=utf-8";
        }
    }

    #endregion

    #region IServiceBehavior

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
        ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            foreach (var endpoint in dispatcher.Endpoints)
            {
                endpoint.DispatchRuntime.MessageInspectors.Add(new ServiceContentTypeMessageInspector());
            }
        }
    }

    public void AddBindingParameters(ServiceDescription serviceDescription,
        ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints,
        BindingParameterCollection bindingParameters)
    {
    }

    public void Validate(ServiceDescription serviceDescription,
        ServiceHostBase serviceHostBase)
    {
    }

    #endregion
}

现在应该按预期工作了!