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

本文关键字:报头 类型 默认 绑定 WebHttpBinding | 更新日期: 2023-09-27 18:11:21

我正在尝试使用默认的WebHttpBinding绑定POST到REST服务。服务只接受"text/xml"作为内容类型,WebHttpBinding发送的是"application/xml, charset-utf=8"。有没有一种方法来改变默认的内容类型,而不使用HttpWebRequest?

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

您可以在操作范围内使用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();
    }
}