简体   繁体   English

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

[英]Default header content-type value used in the WebHttpBinding binding

I'm trying to POST to a REST service using the default WebHttpBinding binding. 我正在尝试使用默认的WebHttpBinding绑定发布到REST服务。 The service only accepts "text/xml" as the content-type and the WebHttpBinding is sending "application/xml, charset-utf=8". 该服务仅接受“ text / xml”作为内容类型,并且WebHttpBinding正在发送“ application / xml,charset-utf = 8”。 Is there a way to change the default content type without using the the HttpWebRequest? 有没有一种方法可以在不使用HttpWebRequest的情况下更改默认内容类型?

You can use the WebOperationContext inside an operation scope to change the outgoing content type of the requests, as shown below. 您可以在操作范围内使用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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM