WebHttpBinding绑定中使用的默认标头内容类型值

时间:2011-10-14 18:01:26

标签: c# wcf rest

我正在尝试使用默认的WebHttpBinding绑定POST到REST服务。该服务仅接受“text / xml”作为内容类型,WebHttpBinding正在发送“application / xml,charset-utf = 8”。有没有办法在不使用HttpWebRequest的情况下更改默认内容类型?

1 个答案:

答案 0 :(得分:4)

您可以使用操作范围内的WebOperationContext来更改请求的传出内容类型,如下所示。

public class StackOverflow_7771645
{
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        string Process();
    }
    public class Service : ITest
    {
        public string Process()
        {
            return "Request content type: " + WebOperationContext.Current.IncomingRequest.ContentType;
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        WebChannelFactory<ITest> factory = new WebChannelFactory<ITest>(new Uri(baseAddress));
        ITest proxy = factory.CreateChannel();
        using (new OperationContextScope((IContextChannel)proxy))
        {
            WebOperationContext.Current.OutgoingRequest.ContentType = "text/xml";
            Console.WriteLine(proxy.Process());
        }

        using (new OperationContextScope((IContextChannel)proxy))
        {
            WebOperationContext.Current.OutgoingRequest.ContentType = "application/xml";
            Console.WriteLine(proxy.Process());
        }

        ((IClientChannel)proxy).Close();
        factory.Close();

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}