开发者

Default header content-type value used in the WebHttpBinding binding

I'm trying to POST to a REST service using the default WebHttpBinding binding. The service only accepts "text/xml" as the content-type and the WebHttpBinding is sending "application/xml, charset-utf=8". Is there a way to change the default content type without using the开发者_StackOverflow中文版 the HttpWebRequest?


You can use the WebOperationContext inside an operation scope to change the outgoing content type of the requests, as shown below.

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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜