WCF charset = utf-8 ответного сообщения не соответствует типу содержимого привязки (application/soap + xml; charset = utf-8)
У меня есть служба WCF в IIS 7.5 с использованием .NET 4.0. У меня также есть приложение WPF, которое я использую в качестве моего клиента, который был создан с помощью Visual Studio 2010 и .NET 4.0. Я добавил ссылку на службу, и когда я пытаюсь вызвать функцию, я получаю следующее исключение.
Приложение типа контента /xml; charset = utf-8 ответного сообщения не соответствует типу содержимого привязки (application/soap + xml; charset = utf-8)
Я могу перейти к службе в веб-браузере, и мои привязки выглядят одинаково между клиентом и сервисом (привязки WsHttp).
Я знаю, что есть много результатов в Google об этой ошибке, но ни одна из них, похоже, не была релевантной/помогла мне в конкретной проблеме. Я попытался установить функции не-HTTP-активации, а также множество других небольших трюков. Кто-нибудь сможет помочь? Благодаря
edit, вот мои конфиги (они довольно длинные)
Client
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="ContentSoap"
closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192"
maxArrayLength="2147483647"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
<binding name="OrderSoap"
closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192"
maxArrayLength="16384" maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
<netTcpBinding>
<binding name="NetTcpBindingEndpoint" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
transactionFlow="false" transferMode="Buffered"
transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" listenBacklog="10"
maxBufferPoolSize="2147000000" maxBufferSize="65536" maxConnections="10"
maxReceivedMessageSize="2147000000">
<readerQuotas maxDepth="32" maxStringContentLength="8192"
maxArrayLength="2147000000" maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:01:00"
enabled="true" />
<security mode="None">
<transport clientCredentialType="Windows"
protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
<wsHttpBinding>
<binding name="WSHttpBinding_IInmateCanteenServiceWeb"
closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192"
maxArrayLength="16384" maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint name="ContentSoap"
address="http://media.team.twvending.net/storeservices/content.asmx"
binding="basicHttpBinding" bindingConfiguration="ContentSoap"
contract="MediaPortContent.ContentSoap" />
<endpoint name="OrderSoap"
address="http://media.team.twvending.net/storeservices/order.asmx"
binding="basicHttpBinding" bindingConfiguration="OrderSoap"
contract="MediaPortOrder.OrderSoap" />
<endpoint name="NetTcpBindingEndpoint"
address="..."
binding="netTcpBinding" bindingConfiguration="NetTcpBindingEndpoint"
contract="WebCallBack.ICallbackService" />
<endpoint name="WSHttpBinding_IInmateCanteenServiceWeb"
address="..."
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IInmateCanteenServiceWeb"
contract="InmateCanteenWeb.IInmateCanteenServiceWeb" />
<endpoint name="WSHttpBinding_ICommAccountingBinding"
address="..."
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IInmateCanteenServiceWeb"
contract="CommAccountingWeb.ICommAccountingWeb" />
</client>
</system.serviceModel>
и сервер
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="httpBehavior">
<!--<webHttp />-->
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceCredentials>
<clientCertificate>
<authentication revocationMode="NoCheck" />
</clientCertificate>
<serviceCertificate findValue="CN=secure.inmatecanteen.com" />
</serviceCredentials>
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="MexBehavior">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="HttpMexBehavior">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="BasicHttpMexBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false"
multipleSiteBindingsEnabled="true" />
<bindings>
<wsHttpBinding>
<binding name="myWsHttpBinding" maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647" messageEncoding="Text">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</wsHttpBinding>
<webHttpBinding>
<binding name="myWebHttpBinding">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
</security>
</binding>
</webHttpBinding>
<basicHttpBinding>
<binding name="myBasicHttpBinding" maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="CommAccountingWeb.CommAccountingWeb"
behaviorConfiguration="HttpMexBehavior">
<endpoint
address=""
behaviorConfiguration="httpBehavior"
binding="webHttpBinding" bindingConfiguration="myWebHttpBinding"
contract="CommAccountingWeb.ICommAccountingWeb" />
<endpoint
address="mex"
binding="mexHttpsBinding"
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="..."></add>
</baseAddresses>
</host>
</service>
<service name="CommAccountingWeb.CommAccountingBasic"
behaviorConfiguration="BasicHttpMexBehavior">
<endpoint
address=""
binding="basicHttpBinding"
bindingConfiguration="myBasicHttpBinding"
contract="CommAccountingWeb.ICommAccountingBasic" />
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="..." />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
Ответы
Ответ 1
Как я и предполагал, ваша конфигурация на стороне клиента выглядит следующим образом:
<endpoint name="WSHttpBinding_ICommAccountingBinding"
address="https://secure.inmatecanteen.com/CommAccountingService/CommAccountingWeb.svc"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IInmateCanteenServiceWeb"
contract="CommAccountingWeb.ICommAccountingWeb" />
Он ожидает wsHttpBinding, но адрес сервера, с которым он подключается:
<service name="CommAccountingWeb.CommAccountingWeb"
behaviorConfiguration="HttpMexBehavior">
<endpoint
address=""
behaviorConfiguration="httpBehavior"
binding="webHttpBinding" bindingConfiguration="myWebHttpBinding"
contract="CommAccountingWeb.ICommAccountingWeb" />
<host>
<baseAddresses>
<add baseAddress="https://secure.inmatecanteen.com/CommAccountingService/CommAccountingWeb.svc"></add>
</baseAddresses>
</host>
</service>
и эта конечная точка сервера использует webHttpBinding.
Поэтому, когда клиент ожидает XML-сообщение SOAP (тип контента: application/soap+xml; charset=utf-8
), конечная точка на стороне сервера является конечной точкой REST, которая возвращает простой XML (контент тип: application/xml; charset=utf-8
)
Решение: вам нужно убедиться, что клиентская и используемая конечная точка сервера синхронизированы с привязками и конфигурацией!
Ответ 2
Как сказал Стивен Уэстбрук says в комментарии к этому ответу:
Добавьте ?wsdl
к своему адресу конечной точки клиента, и вам больше повезет с сервисом. ?wsdl
важен - это означает, что браузер просто получает "язык описания веб-служб" для службы, а не вызывает службу.
У меня была та же проблема, и добавление ?wsdl
решило мою головную боль.
Ответ 3
Я столкнулся с подобной ошибкой при создании клиентской службы для одной из существующих WebService на стороне сервера. Я мог бы исправить это, используя транспортный протокол SOAP 1.1 на клиенте. Как-то мыло 1.2 дает/ожидает другой формат. Это связано с различием между BasicHttpBinding vs WebHttpBinding и WsHttpBinding.
Ответ 4
У меня возникла эта проблема после того, как я добавил метод, который возвратил коллекцию экземпляров базового класса, у которого не было атрибута [KnownType]
, который разрешил конкретный экземпляр.
С помощью атрибута [KnownType] проблема исчезла.
[ServiceContract]
public interface IService {
[OperationContract]
IEnumerable<ItemBase> GetItems();
}
[DataContract]
// [KnownType(typeof(RealItemA))] <--- without these attributes you will get a problem
// [KnownType(typeof(RealItemB))]
public class ItemBase {
}
[DataContract]
public class RealItemA : ItemBase {
}
[DataContract]
public class RealItemB : ITemBase {
}
Ответ 5
в моем случае такая же ошибка была вызвана отсутствием
[datacontract]
[datamember]
в возвращаемом типе данных.
Сообщение об ошибке действительно вводило в заблуждение.
Ответ 6
Убедитесь, что вы не вносили изменений в привязки, контракт и конечные точки, сгенерированные в app.config, при добавлении ссылки на службу.
Добавьте MessageEncoding как Mtom в .NET-код, а затем проверьте, все ли вы получили сообщение.
Я попытался объяснить создание потребления службы wcf с использованием протокола soap для wshttpbinding и basichttpbinding и проблем, с которыми сталкиваются здесь:
http://www.writeulearn.com/consume-wcf-soap-service-csharp/
Пожалуйста, пройдите через него.
Ответ 7
У меня есть эта ошибка из-за различной версии Syste.Web.MVC DLL. Вы можете отправить ответ здесь в другой вопрос о переполнении стека.