Sharepoint custom WCF Rest service not using maxReceivedMessageSize - wcf

I'm building custom WCF Rest service for Sharepoint 2010. Main task of service is to download and upload some files to/from Sharepoint. Download is working as expected, but when uploading file larger than 64Kb I get following error :
The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.
Stack trace :
System.ServiceModel.Channels.HttpInput.ThrowHttpProtocolException(String message, HttpStatusCode statusCode, String statusDescription)
System.ServiceModel.Channels.HttpInput.ThrowMaxReceivedMessageSizeExceeded()
System.ServiceModel.Channels.HttpInput.GetMessageBuffer()
System.ServiceModel.Channels.HttpInput.ReadBufferedMessage(Stream inputStream)
System.ServiceModel.Channels.HttpInput.ParseIncomingMessage(Exception& requestException)
System.ServiceModel.Channels.HttpRequestContext.CreateMessage()
System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, ItemDequeuedCallback callback)
System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
System.ServiceModel.PartialTrustHelpers.PartialTrustInvoke(ContextCallback callback, Object state)
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequestWithFlow(Object state)
System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()
System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()
System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)
System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
So my first guess was to increase maximum message size through custom configuration as follows :
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="Project.Poc.StorageServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="Project.Poc.IStorageService" behaviorConfiguration="Project.Poc.StorageServiceBehavior">
<endpoint binding="webHttpBinding" bindingConfiguration="StreamedRequestWebBinding" contract="Project.Poc.IStorageService"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="StreamedRequestWebBinding"
sendTimeout="00:05:00"
openTimeout="00:05:00"
receiveTimeout="00:05:00"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
transferMode="StreamedRequest">
<readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" />
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
After applying this, deploying my WSP and doing IIS reset error was still there. Same HTTP 400 with above information from WCF trace. So somehow my web.config configuration is not good because WCF service is not using it?
Upload files that are smaller then 64KB is working as expected.
Also this is My IStorageService.cs definition :
namespace Project.Poc
{
[ServiceContract]
public interface IStorageService
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/Download?path={path}")]
Stream DownloadFile(string path);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/Upload?path={path}")]
void UploadFile(string path, Stream content);
}
}
And also StorageService.svc in ISAPI folder where my web.config is also :
<%# ServiceHost Language="C#" Debug="true" Service="Project.Poc.StorageService, Project.Poc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d2ed6a8d86479f52" CodeBehind="StorageService.svc.cs" Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
I tried every other variation of web.config that I found googling but with no luck. What can be cause of this? Any help is more than welcome.
Also if you need any other part of the source code, just let me know. I will update my question.
Thank you in advance!

I'd review your client config - to be sure binding configuration has same attribute
maxReceivedMessageSize="2147483647".
Also, I'd try to add to your bindings (both client and service)
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
If both of this will not help - try to use SvcTraceViewer to find out where the error comes from (client when sending, server, ...)

Related

Wcf WS-Security server

i have created service with such binding configuration:
<bindings>
<customBinding>
<binding name="DefaultBinding">
<textMessageEncoding messageVersion="Soap12" />
<httpTransport />
</binding>
</customBinding>
</bindings>
And when my service receives message starting like this:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
<s:Header>
<Security s:mustUnderstand="1" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<UsernameToken>
<Username>
</Username>
<Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">...</Password>
<Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">KWVa4abCrEemOMT55VEZkgIAAAAAAA==</Nonce>
<Created xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2013-08-28T13:29:05.966Z</Created>
</UsernameToken>
</Security>
...
It produces error:
The header 'Security' from the namespace 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' was not understood ...
I also tried:
<wsHttpBinding>
<binding name="DefaultBinding">
<security mode="Message" />
</binding>
</wsHttpBinding>
How i can process this header or ignore it ?
Update
As i understood i need username over insecure transport, so i tried:
<customBinding>
<binding
name="DefaultBinding">
<textMessageEncoding messageVersion="Soap12" />
<security authenticationMode="UserNameOverTransport" allowInsecureTransport="True">
</security>
<httpTransport>
</httpTransport>
</binding>
</customBinding>
I also tried CUB:
<bindings>
<clearUsernameBinding>
<binding name="myClearUsernameBinding" messageVersion="Soap12">
</binding>
</clearUsernameBinding>
</bindings>
Both ends with error on client: An error occurred when verifying security for message. But it works with test CUB's client. What could be wrong ?
CUB's envelope's header.
Test client's header.
Solution was simple:
Create service behavior
Create dispatch message inspector
Add created service behavior to server
And then just parse or just delete unused "mustUnderstand" headers.
Step 1:
public class WSSecurityBehavior : IServiceBehavior {
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) {
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection bindingParameters) {
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) {
var endpoints = serviceHostBase
.ChannelDispatchers
.Cast<ChannelDispatcher>()
.SelectMany(dispatcher => dispatcher.Endpoints);
foreach (var endpoint in endpoints)
endpoint.DispatchRuntime.MessageInspectors.Add(new WSSecurityInspector());
}
}
Step 2:
public class WSSecurityInspector : IDispatchMessageInspector {
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) {
var headerPosition = request.Headers.FindHeader("Security",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
if (headerPosition > -1)
request.Headers.RemoveAt(headerPosition);
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState) {
}
}
Step 3:
Host.Description.Behaviors.Add(new WSSecurityBehavior());
You've got a mismatch in the soap structure/contract you're exchanging between the client and host. The structure of the messages exchanged between the client and host (including the namespace) must match exactly. If they don't, you get this error.
What you want to do is get Fiddler running on your host. Then, running Fiddler as an man-in-the-middle proxy, resend the request from your client machine. When the request/response is finished, examine the messages in Fiddler, particularlly the namespace and structure differences between the request and response and there you should find the problem.
The client is trying to authenticate to your server using user/pass in the message level. You need to decide if this is expected behavior, in which case you need to configure your service to do username authentication. This is not just a matter of setting a binding, you need to decide how you authenticate users (e.g. via a database, windows credentials etc). Once you know that you should be able to use a binding like this:
<customBinding>
<binding name="NewBinding0">
<textMessageEncoding />
<security authenticationMode="UserNameOverTransport">
<secureConversationBootstrap />
</security>
<httpsTransport />
</binding>
</customBinding>
I cannot be sure that this is what you need since you did not publish the full soap envelope. You might need to set messageVersion attribute on the text encoding element, or use CUB in case there is no SSL.
Then you need to configure how you are going to verify the username. One example is here.
you can use basicHttpBinding, download the project and sample code from this post for password digest in wcf PasswordDigest Auth this is my configuration with this implementation (i edited some code for custom needs but this solution works fine).
Create a binding:
<bindings>
<basicHttpBinding>
<binding name="securityBinding">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
And after set a behavior
<behavior name="securityBehavior">
<DataMessageTracer/>
<serviceCredentials type="WCF.SecurityExtensions.ServiceCredentialsEx, WCF.SecurityExtensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<serviceCertificate findValue="hypori2.zed.pa" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"/>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyService.Utils.PassValidator, MyService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</serviceCredentials>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>

programmatically create netTcp binding with certificates

I have a general purpose hosting service for WCF (.net v4). It allows for multiple agents to be dropped in plug-in style with each agent having its own config file. It was written as a service since all sites will not have IIS or WAS intalled but we can specify .net v4 and our custome service.
We have had no issues with HTTP, HTTPS or TCP (without credentials). When we add, a certificate to the server it appears to start without an issue. As soon as we attempt to call the servie we get a channel fault. We wrote a small self-hosting program that uses the config file rather than programmatically creating the endpoing and it works without any issue. We can only speculate we missed a setting but cannot identify which.
The error we get is shown below. It appears that for some reason the client it trying to set up a dual-channel tcp connection which we did not configure in the host.
Protocol Type application/negotiate was sent to a service that does not support that type of upgrade.
System.ServiceModel.Channels.ServerSessionPreambleConnectionReader.ServerFramingDuplexSessionChannel.ProcessUpgradeRequest(TimeoutHelper& timeoutHelper)
System.ServiceModel.Channels.ServerSessionPreambleConnectionReader.ServerFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
System.ServiceModel.Channels.CommunicationObject.Open()
System.ServiceModel.Channels.ReliableChannelListener`3.HandleAcceptComplete(TInnerChannel channel)
System.ServiceModel.Channels.ReliableChannelListener`3.OnAcceptCompleted(IAsyncResult result)
System.ServiceModel.Channels.ReliableChannelListener`3.OnAcceptCompletedStatic(IAsyncResult result)
System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.ServiceModel.Diagnostics.TraceUtility.<>c__DisplayClass4.<CallbackGenerator>b__2(AsyncCallback callback, IAsyncResult result)
System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
System.Runtime.InputQueue`1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)
System.Runtime.InputQueue`1.EnqueueAndDispatch(T item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
System.ServiceModel.Channels.TcpDuplexChannelListener.System.ServiceModel.Channels.ISessionPreambleHandler.HandleServerSessionPreamble(ServerSessionPreambleConnectionReader preambleReader, ConnectionDemuxer connectionDemuxer)
System.ServiceModel.Channels.ConnectionOrientedTransportManager`1.OnHandleServerSessionPreamble(ServerSessionPreambleConnectionReader serverSessionPreambleReader, ConnectionDemuxer connectionDemuxer)
System.ServiceModel.Channels.ConnectionDemuxer.OnSessionPreambleKnown(ServerSessionPreambleConnectionReader serverSessionPreambleReader)
System.ServiceModel.Channels.ServerSessionPreambleConnectionReader.ContinueReading()
System.ServiceModel.Channels.ServerSessionPreambleConnectionReader.StartReading(Action`1 viaDelegate, TimeSpan receiveTimeout)
System.ServiceModel.Channels.ConnectionDemuxer.OnDuplexConnection(IConnection connection, Action connectionDequeuedCallback, Int64 streamPosition, Int32 offset, Int32 size, TimeSpan timeout)
System.ServiceModel.Channels.ConnectionDemuxer.OnConnectionModeKnownCore(ConnectionModeReader modeReader, Boolean isCached)
System.ServiceModel.Channels.ConnectionDemuxer.OnConnectionModeKnown(ConnectionModeReader modeReader)
System.ServiceModel.Channels.ConnectionModeReader.Complete()
System.ServiceModel.Channels.ConnectionModeReader.ReadCallback(Object state)
System.ServiceModel.Channels.TracingConnection.TracingConnectionState.ExecuteCallback()
System.ServiceModel.Channels.TracingConnection.WaitCallback(Object state)
System.ServiceModel.Channels.SocketConnection.FinishRead()
System.ServiceModel.Channels.SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead)
System.ServiceModel.Channels.OverlappedContext.CompleteCallback(UInt32 error, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
CLIENT:
<netTcpBinding>
<binding name="NetTcpEndPoint_ISolutionsDataAccessorV01" 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="524288" maxBufferSize="65536" maxConnections="10"
maxReceivedMessageSize="65536">
<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="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
</bindings>
<client>
<endpoint address="net.tcp://localhost:1177/TcpService" binding="netTcpBinding"
bindingConfiguration="NetTcpEndPoint_ISolutionsDataAccessorV01"
contract="sDAL.ISolutionsDataAccessorV01" name="NetTcpEndPoint_ISolutionsDataAccessorV01">
<identity>
<userPrincipalName value="abc#xyz.com" />
</identity>
</endpoint>
</client>
</system.serviceModel>
SERVICE:
-->
<behaviors>
<serviceBehaviors>
<behavior name="SolutionsDALServiceBehavior">
<serviceCredentials>
<serviceCertificate findValue="STSTestCert"
x509FindType="FindByIssuerName" />
</serviceCredentials>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<!-- <serviceMetadata httpGetEnabled="true"/> -->
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>

Failed to Execute URL when calling a WCF service with Windows authentication

I am having a problem with a WCF service using Windows authentication on one of the servers I am deploying it to (it's a Windows Server 2008 R2 machine), while it works flawlessly on all other machines I have access to (Windows 7, Windows Server 2008 and Windows Server 2008 R2). I managed to reproduce the issue with a really simple sample application which more or less completely excludes my code as the cause of the problem.
The minimum application I can reproduce the issue with is a minor modification of the WCF service project template:
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
}
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}\nUsername: {1}",
value,
ServiceSecurityContext.Current == null ?
"<null>" :
ServiceSecurityContext.Current.PrimaryIdentity.Name);
}
}
Basically I enabled ASP.NET compatibility (I need it because the actual code uses an HttpHandler for authentication) and the username of the authenticated user is returned.
The contents of web.config are as follows:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Windows"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="HttpWindowsBinding" maxReceivedMessageSize="2147483647">
<readerQuotas maxBytesPerRead="2147483647" maxArrayLength="2147483647" maxStringContentLength="2147483647" maxNameTableCharCount="2147483647" maxDepth="2147483647"/>
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
<services>
<service name="TestService.Service1" behaviorConfiguration="ServiceBehavior">
<endpoint address=""
binding="basicHttpBinding"
bindingConfiguration="HttpWindowsBinding"
contract="TestService.IService1" />
<endpoint address="problem"
binding="basicHttpBinding"
bindingConfiguration="HttpWindowsBinding"
contract="TestService.IService1" />
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Notice the two endpoints: one with the default address, the other one with a relative address. Calling the first one succeeds even on the problematic server, while the call to the second one fails with following error:
Exception type: HttpException
Exception message: Failed to Execute URL.
at System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.BeginExecuteUrl(String url, String method, String childHeaders, Boolean sendHeaders, Boolean addUserIndo, IntPtr token, String name, String authType, Byte[] entity, AsyncCallback cb, Object state)
at System.Web.HttpResponse.BeginExecuteUrlForEntireResponse(String pathOverride, NameValueCollection requestHeaders, AsyncCallback cb, Object state)
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
The call only fails when the classic pipeline is used (I need it because of the HttpHandler, but the issue can be reproduced even without it). With integrated pipeline the problem is gone. Also if I disable Windows authentication, the problem is gone as well:
<binding name="HttpBinding" maxReceivedMessageSize="2147483647">
<readerQuotas maxBytesPerRead="2147483647" maxArrayLength="2147483647" maxStringContentLength="2147483647" maxNameTableCharCount="2147483647" maxDepth="2147483647"/>
<security mode="None">
<transport clientCredentialType="None" />
</security>
</binding>
I have noticed another detail with an HttpHandler registered. The value of HttpRequest.CurrentExecutionFilePath property for the endpoint with the relative address differs between the problematic server (~/Service1.svc/problem) and the working servers (~/Service1.svc). Although I'm not that well familiar with IIS, I suspect this could hint at the cause of the problem - maybe something related to the routing of requests?
I am running out of ideas therefore I'm posting this here in the hope the someone will recognize what the problem could be. Any suggestion are welcome.
Do you have URL rewriting on IIS turned on? This smells like a permission issue of some sort. What is the difference between Classic and Integrated pipeline mode in IIS7? Might be helpful.
The problem may be the address "~/Service1.svc/problem"
When the address is "~/Service1.svc" the call hits the svc file, and uses the information in the file to find the interface and then the configuration for that interface.
When you use a relative address without a svc file, it looks at the address in the config file.
Do you have a directory "Service1.svc" on one of the servers, or is the address without the ".svc" on the server where it works?

Vague WCF Error on client side when processing a large object graph

I am calling a WCF service from a SharePoint site and getting an error on the client with below details, when relatively large object graph is returned.
On debugging the service I can see that is contructs the object correctly and the method returns the final object (that has the list of other objects) correctly. But I get exception on client side on the service method call.
Thie service/method works fine in most of the cases. Below are the service configurations (apologies for bad formatting)
Service Config:
<system.serviceModel>
<services>
<service behaviorConfiguration="StandardServiceBehaviour" name="Thd.K2.Web.DataServicesLibrary.Common.Services.AdminService">
<endpoint address="soap" binding="basicHttpBinding" name="AdminService" contract="Thd.K2.Web.DataServicesLibrary.Common.Interfaces.IAdminService" />
<endpoint address="mex" binding="mexHttpBinding" name="Metadata" contract="IMetadataExchange" kind="mexEndpoint" endpointConfiguration="" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="StandardServiceBehaviour">
<serviceMetadata httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="customBinding" hostNameComparisonMode="StrongWildcard" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00" maxReceivedMessageSize="1000000" maxBufferSize="1000000" maxBufferPoolSize="1000000" transferMode="Buffered" messageEncoding="Text" textEncoding="utf-8" bypassProxyOnLocal="false" useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="214748364" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="Transport" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding name="webBinding" bypassProxyOnLocal="true" useDefaultWebProxy="false" hostNameComparisonMode="WeakWildcard" sendTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="00:05:00" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647">
<readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" />
<security mode="Transport">
</security>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
Client method to create service instance
public static TServiceType GetServiceClient<TServiceType>(ConnStringsType connectionStringType, Page callingPage)
where TServiceType : class
{
var spUrl = GetConnectionString(connectionStringType, callingPage);
var result = new BasicHttpBinding(BasicHttpSecurityMode.None);
if(spUrl.ToLower().StartsWith("https"))
{
result = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
}
result.MaxReceivedMessageSize = int.MaxValue - 1;
result.MaxBufferSize = int.MaxValue-1;
if (!string.IsNullOrEmpty(spUrl))
{
return (TServiceType)Activator.CreateInstance(typeof(TServiceType), result, new EndpointAddress(spUrl));
}
return null;
}
Error:
An error occurred while receiving the HTTP response to http://localhost:90/AdminService.svc/soap. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
Stack:
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at IAdminService.GetBlackoutPeriodsByDescription(String lang, String description)
at AdminServiceClient.GetBlackoutPeriodsByDescription(String lang, String description)
at EditBlackoutDates.LoadBlackout(String description)
I think this is about MaxItemsInObjectGraph property. Here is the answer to the similar problem.
#paramosh - Thanks a lot!!!
That did the trick. For others reference I was actually using a Non-RESTful WCF service. Hence I modified the solution as below
Calling below function before the web svc method call:
private void ExpandObjectGraphItems(AdminServiceClient svc)
{
var operations = svc.Endpoint.Contract.Operations;
foreach (var operation in operations)
{
var dataContractBehavior = operation.Behaviors.Find<System.ServiceModel.Description.DataContractSerializerOperationBehavior>();
if (dataContractBehavior != null)
{
dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
}
}
}
Added following attribute to service config:
<behavior name="StandardServiceBehaviour">
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>

The message with Action '' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher

I try to solve this since few days ... I get this error only when call soap service, in rest all ok.
My config in client (in service is the same, only not have client section)
<system.serviceModel>
<client>
<endpoint address="soap" binding="customHttpBinding" bindingConfiguration="MyCustomHttpBinding" name="Soap" contract="ServiceModel.IService" />
</client>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
<serviceActivations>
<add relativeAddress="Service.svc" service="ServiceModel.Service" />
</serviceActivations>
</serviceHostingEnvironment>
<bindings>
<customBinding>
<binding name="MyCustomHttpBinding">
<textMessageEncoding messageVersion="Soap12" />
<context protectionLevel ="None"/>
<httpTransport transferMode ="Buffered" />
</binding>
</customBinding>
<webHttpBinding>
<binding name="webHttpBindingSettings" closeTimeout="00:01:00" transferMode="Streamed" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="524288" maxReceivedMessageSize="654321">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" />
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="ServiceModel.Service" behaviorConfiguration="MetadataBehavior">
<endpoint address="soap" binding="customBinding" bindingConfiguration="MyCustomHttpBinding" name="Soap" contract="ServiceModel.IService" />
<endpoint address="rest" behaviorConfiguration="jsonBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingSettings" name="Json" contract="ServiceModel.IService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://dev.add.com/Service.svc/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MetadataBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="jsonBehavior">
<webHttp automaticFormatSelectionEnabled="true" helpEnabled="true" />
</behavior>
</endpointBehaviors>
</behaviors>
my service
[ServiceContract(Namespace = "ServiceModel")]
public interface IService
{
[OperationContract]
[WebInvoke()]
GetInfoResponse GetRestData(GetInfoRequest message);
[OperationContract]
[WebInvoke()]
GetInfoResponse GetSoapData(GetInfoRequest message);
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)]
string Save(Stream message);
}
call service
GetInfoRequest message = CheckedFields;
string soap = #"<?xml version=""1.0"" encoding=""utf-8""?>
<soap12:Envelope xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
<soap12:Header>
<Action soap12:mustUnderstand=""1"" xmlns=""http://www.w3.org/2005/08/addressing"">ServiceModel/IService/GetSoapData</Action>
</soap12:Header>
<soap12:Body>
<GetInfoRequest xmlns=""ServiceModel"">
<Data xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""/>
</GetInfoRequest>
</soap12:Body>
</soap12:Envelope>";
XmlSerializer serializer = new XmlSerializer(typeof(GetInfoRequest));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.add.renault.com/Service.svc/soap");
MemoryStream stream1 = new MemoryStream();
serializer.Serialize(stream1, message);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
string t = sr.ReadToEnd();
t = t.Remove(0, 22).Trim();
t = string.Format(soap, t);
ASCIIEncoding encoding = new ASCIIEncoding();
request.Timeout = 99999999;
request.ContentLength = t.Length;
request.Method = "POST";
request.ContentType = "application/soap+xml; charset=utf-8";
request.Accept = "application/soap+xml; charset=utf-8";
using (Stream stm = request.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(t);
}
}
var response = (HttpWebResponse)request.GetResponse();
var abc = new StreamReader(response.GetResponseStream());
Stack Trace
System.ServiceModel.Dispatcher.ErrorBehavior.ThrowAndCatch(Exception e, Message message)
System.ServiceModel.Dispatcher.ChannelHandler.ReplyFailure(RequestContext request, Message fault, String action, String reason, FaultCode code)
System.ServiceModel.Dispatcher.ChannelHandler.ReplyFailure(RequestContext request, FaultCode code, String reason, String action)
System.ServiceModel.Dispatcher.ChannelHandler.ReplyContractFilterDidNotMatch(RequestContext request)
System.ServiceModel.Dispatcher.ChannelHandler.EnsureChannelAndEndpoint(RequestContext request)
System.ServiceModel.Dispatcher.ChannelHandler.TryRetrievingInstanceContext(RequestContext request)
System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
System.Runtime.InputQueue`1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)
System.Runtime.InputQueue`1.EnqueueAndDispatch(T item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
System.ServiceModel.Channels.SingletonChannelAcceptor`3.Enqueue(QueueItemType item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback)
System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
The problem was that in config I use Soap12 but message which I send using WebHttpRequest contains Soap Header with non Soap12 element.
The action you have hardcoded in your request string is wrong. The default action will probably be ServiceModel/IService1/GetSoapData.
[I would strongly recommend using a standard WCF client to test your SOAP service. You can turn diagnostics and log messages if you need to examine the actual XML generated. WCF provides lots of capabilities to control the messages it receives/sends. Unless you understand the implementation of all the configuration switches you are using it is very difficult to predict what message changes are required.]