简体   繁体   中英

Cannot process the message because the content type 'application / xml' was not the expected type 'application / soap + xml; charset = utf-8 '

The remote server returned an error: (415) Cannot process the message because the content type 'application / xml' was not the expected type 'application / soap + xml; charset = utf-8 '

I just try to launch my self host. I have 2 endpoints with Basic Authentication. So I had to use wsHttpBinding for that. CreateUser endpoint should use XML format and RemoveUser endpoint - json format.

I attached my selfhost app.config, client main function and contract.

server app.config

<services>
  <service name="Web.Service.Core.Services.UserContract"
           behaviorConfiguration="AuthBehavior" >
    <endpoint address="CreateUser"
              binding="wsHttpBinding"
              bindingNamespace="http://localhost/Auth/"
              contract="Web.Service.Library.Contracts.IUserContract" />
    <endpoint address="RemoveUser"
              binding="wsHttpBinding"
              contract="Web.Service.Library.Contracts.IUserContract" />

IUserContract.cs

[ServiceContract(Namespace = "http://localhost/Auth/", ProtectionLevel = ProtectionLevel.None)]
[XmlSerializerFormat]
public interface IUserContract
{
    [OperationContract]
    [WebInvoke(Method = "POST",
        UriTemplate = "Auth/CreateUser",
        RequestFormat = WebMessageFormat.Xml,
        ResponseFormat = WebMessageFormat.Xml,
        BodyStyle = WebMessageBodyStyle.Wrapped)]
    Response CreateUser(Stream xml);

    [OperationContract]
    [WebInvoke(Method = "POST",
        UriTemplate = "Auth/RemoveUser",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped)]
    Response RemoveUser(Stream stream);

client main()

var webRequest = (HttpWebRequest) WebRequest.Create(CreateUserUrl);
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.ContentLength = data.Length;
var rqStream = webRequest.GetRequestStream();
rqStream.Write(data, 0, data.Length);
rqStream.Close();
var webResponse = webRequest.GetResponse();
var rsStream = webResponse.GetResponseStream();
var responseXml = new StreamReader(rsStream);
var s = responseXml.ReadToEnd();

When we use wshttpbinding to create WCF service, the service based on the web service speficification, and use Simple Object Access Protocol to communicate. We could check the communication details by using fiddler.
在此处输入图片说明
The content-type is Application/soap+xml instead of the Application/xml, and the request body format based on SOAP envelop.
https://en.wikipedia.org/wiki/SOAP
This kind of web service is called SOAP web service. Ordinarily, we call the service by using the client proxy class.

   ServiceReference1.ServiceClient client = new ServiceClient();
            try
            {
                var result = client.GetData();
                Console.WriteLine(result);
            }
            catch (Exception)
            {

                throw;
            }

https://docs.microsoft.com/en-us/dotnet/framework/wcf/accessing-services-using-a-wcf-client
The way you call a service usually applies to Restful-style service.
https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design
Instantiate the HttpClient class and custom the request body. Under this circumstance, we should use WebHttpBinding in WCF to create the service. Please refer to my reply.
How to fix "ERR_ABORTED 400 (Bad Request)" error with Jquery call to C# WCF service?
Feel free to let me know if there is anything I can help with.

Updated.

class Program
{
    /// <summary>
    /// https webhttpbinding.
    /// </summary>
    /// <param name="args"></param>
    static void Main(string[] args)
    {
        Uri uri = new Uri("https://localhost:4386");
        WebHttpBinding binding = new WebHttpBinding();
        binding.Security.Mode = WebHttpSecurityMode.Transport;
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;


        using (WebServiceHost sh = new WebServiceHost(typeof(TestService), uri))
        {
            sh.AddServiceEndpoint(typeof(ITestService), binding, "");
            ServiceMetadataBehavior smb;
            smb = sh.Description.Behaviors.Find<ServiceMetadataBehavior>();
            if (smb == null)
            {
                smb = new ServiceMetadataBehavior()
                {
                    //HttpsGetEnabled = true
                };
                sh.Description.Behaviors.Add(smb);

            }
            Binding mexbinding = MetadataExchangeBindings.CreateMexHttpsBinding();
            sh.AddServiceEndpoint(typeof(IMetadataExchange), mexbinding, "mex");


            sh.Opened += delegate
            {
                Console.WriteLine("service is ready");
            };
            sh.Closed += delegate
            {
                Console.WriteLine("service is closed");
            };
            sh.Open();

            Console.ReadLine();

            sh.Close();
        }
    }
}
[ServiceContract]
public interface ITestService
{
    [OperationContract]
    [WebGet(ResponseFormat =WebMessageFormat.Json)]
    string GetResult();
}

[ServiceBehavior]
public class TestService : ITestService
{
    public string GetResult()
    {
        return $"Hello, busy World. {DateTime.Now.ToShortTimeString()}";
    }
}

Bind a certificate to the port(Powershell command).

    netsh http add sslcert ipport=0.0.0.0:4386 certhash=cbc81f77ed01a9784a12483030ccd497f01be71c App
id='{61466809-CD17-4E31-B87B-E89B003FABFA}'

Result.
在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question HTTP 415 Cannot process the message because the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8' Cannot process the message because the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8' HTTP/1.1 415 Cannot process the message because the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8' WCF ERROR: (415) content type 'application/x-www-form-urlencoded' was not the expected type 'application/soap+xml; charset=utf-8' WCF Membership Provider throws error: content type 'application/json; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8' The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8) The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8), WCF wcf + The content type text/html of the response message does not match the content type of the binding (application/soap+xml; charset=utf-8) Getting the error Client found response content type of 'text/html; charset=utf-8', but expected 'application/soap+xml'? WCF SOAP service cannot process the message because it sends multipart message and expects 'text/xml; charset=utf-8'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM