Attempting to consume CRM SOAP endpoint occasionally throws "User id is invalid" - wcf

We have an on-premise CRM with roll-up 13. Some of the forms need to be populated with external data that comes from multiple sources and needs to be pre-processed. To do this, we developed a custom WCF service that runs on the same server as CRM and is hosted in IIS as a virtual app in CRM's website (to avoid cross-domain scripting issues) and exposes a REST endpoint to the javascript that runs in CRM forms. The javascript makes requests, the service collects and processes data and then replies back to javascript with some nice simple JSON.
Since some of the data we need comes from CRM itself, we figured we'll let the service collect that also (using CRM's SOAP endpoint), rather than making the requests from javascript to CRM web services directly. We have pass-through authentication set up in IIS, so our custom app makes requests to CRM while impersonating the user that's logged into CRM.
Most of the time, this all works great. However, once we got more testers we started noticing that occasionally CRM will stop replying to our service for some user, throwing an exception. If that user closes the browser and re-opens it and then tries the exact same operation, it all starts working again. I turned on tracing on the CRM server and found that when this happens, CRM is logging "Crm Exception: Message: The user Id is invalid., ErrorCode: -2147214049". Full trace below:
[2013-09-10 08:54:14.492] Process: w3wp |Organization:00000000-0000-0000-0000-000000000000 |Thread: 69 |Category: Exception |User: 00000000-0000-0000-0000-000000000000 |Level: Error |ReqId: 4b901457-a545-4844-9ce8-b017d3833087 | CrmException..ctor ilOffset = 0x36
at CrmException..ctor(Int32 errorCode, Object[] arguments) ilOffset = 0x36
at SecurityLibrary.GetPrivilegedUserCallerAndBusinessGuidsFromThread(WindowsIdentity identity, IOrganizationContext context) ilOffset = 0x6F
at SecurityLibrary.GetCallerAndBusinessGuidsFromThread(WindowsIdentity identity, Guid organizationId, LocatorServiceContext locatorServiceContext) ilOffset = 0x56
at UserManagementFactory.ValidateSpecialUser(WindowsIdentity identity, Guid organizationId) ilOffset = 0x1E
at WindowsIdentityAuthorizationManager.Authenticate(OperationContext operationContext) ilOffset = 0x185
at WindowsIdentityAuthorizationManager.CheckAccessCore(OperationContext operationContext) ilOffset = 0x22
at AuthorizationBehavior.Authorize(MessageRpc& rpc) ilOffset = 0x28
at ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) ilOffset = 0x293
at MessageRpc.Process(Boolean isOperationContextSet) ilOffset = 0x62
at ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext) ilOffset = 0x1D7
at ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext) ilOffset = 0xF1
at ChannelHandler.AsyncMessagePump(IAsyncResult result) ilOffset = 0x21
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) ilOffset = 0x0
at AsyncResult.Complete(Boolean completedSynchronously) ilOffset = 0xC2
at ReceiveItemAndVerifySecurityAsyncResult`2.InnerTryReceiveCompletedCallback(IAsyncResult result) ilOffset = 0x55
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) ilOffset = 0x0
at AsyncResult.Complete(Boolean completedSynchronously) ilOffset = 0xC2
at AsyncQueueReader.Set(Item item) ilOffset = 0x21
at InputQueue`1.Dispatch() ilOffset = 0x121
at ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) ilOffset = 0x22
at IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) ilOffset = 0x5
at _IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) ilOffset = 0x3C
>Crm Exception: Message: The user Id is invalid., ErrorCode: -2147214049
[2013-09-10 08:54:14.508] Process: w3wp |Organization:00000000-0000-0000-0000-000000000000 |Thread: 69 |Category: Platform.Sdk |User: 00000000-0000-0000-0000-000000000000 |Level: Error |ReqId: 4b901457-a545-4844-9ce8-b017d3833087 | ServiceModelTraceRedirector.TraceData ilOffset = 0x45
><TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error"><TraceIdentifier>http://msdn.microsoft.com/en-CA/library/System.ServiceModel.Diagnostics.TraceHandledException.aspx</TraceIdentifier><Description>Handling an exception.</Description><AppDomain>/LM/W3SVC/1/ROOT-6-130232384646037254</AppDomain><Exception><ExceptionType>Microsoft.Crm.CrmException, Microsoft.Crm.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</ExceptionType><Message>The user Id is invalid.</Message><StackTrace> at Microsoft.Crm.BusinessEntities.SecurityLibrary.GetPrivilegedUserCallerAndBusinessGuidsFromThread(WindowsIdentity identity, IOrganizationContext context)
> at Microsoft.Crm.BusinessEntities.SecurityLibrary.GetCallerAndBusinessGuidsFromThread(WindowsIdentity identity, Guid organizationId, LocatorServiceContext locatorServiceContext)
> at Microsoft.Crm.Authentication.UserManagementFactory.ValidateSpecialUser(WindowsIdentity identity, Guid organizationId)
> at Microsoft.Crm.Authentication.WindowsIdentityAuthorizationManager.Authenticate(OperationContext operationContext)
> at Microsoft.Crm.Authentication.WindowsIdentityAuthorizationManager.CheckAccessCore(OperationContext operationContext)
> at System.ServiceModel.Dispatcher.AuthorizationBehavior.Authorize(MessageRpc&amp; rpc)
> at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc)
> at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace><ExceptionString>Microsoft.Crm.CrmException: The user Id is invalid.
> at Microsoft.Crm.BusinessEntities.SecurityLibrary.GetPrivilegedUserCallerAndBusinessGuidsFromThread(WindowsIdentity identity, IOrganizationContext context)
> at Microsoft.Crm.BusinessEntities.SecurityLibrary.GetCallerAndBusinessGuidsFromThread(WindowsIdentity identity, Guid organizationId, LocatorServiceContext locatorServiceContext)
> at Microsoft.Crm.Authentication.UserManagementFactory.ValidateSpecialUser(WindowsIdentity identity, Guid organizationId)
> at Microsoft.Crm.Authentication.WindowsIdentityAuthorizationManager.Authenticate(OperationContext operationContext)
> at Microsoft.Crm.Authentication.WindowsIdentityAuthorizationManager.CheckAccessCore(OperationContext operationContext)
> at System.ServiceModel.Dispatcher.AuthorizationBehavior.Authorize(MessageRpc&amp; rpc)
> at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc)
> at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</ExceptionString></Exception></TraceRecord>
It seems to me like a security token or cached credentials of some sort expire or become invalid somehow, and our app can no longer authenticate to CRM. Re-opening IE fixes this. We haven't found a way to reliably reproduce this, but it happens often enough to be a concern to the users. Anyone have any ideas?

One workaround is to scrap pass through authentication. Instead change your web services to always authenticate using the same CRM user id and impersonate users once successfully authenticated.
Set up a new user (e.g. "CRM Web Service User") or pick an existing user account. Make sure this user has a security role with the right to impersonate other users, I believe the correct setting for this is under business management on the security role and is called "Act on behalf of other users".
Once you've set this user up you will need to tweak your web services so that they can accept a User ID from the caller. The web service will use its configured "CRM Web Service User" user to authenticate against CRM, but will then impersonate the user id passed in by the caller (which will in turn apply the correct rights for this user).
This might require a little extra work, but it gives you a bit more control over the authentication and how to handle failures.

Related

SID of the target principal could not be resolved.

I delpoyed my web application (which uses LDAP) on windows server 2016. It is throwing below error. Though I am able to access same ADLDS instance using ADSI or C# console application (created utility to test connectivity). But not sure why its throwing error with web application. Please suggest.
Server Error in '/' Application.
**While trying to resolve a cross-store reference, the SID of the target principal could not be resolved. The error code is 1722.**
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.DirectoryServices.AccountManagement.PrincipalOperationException: While trying to resolve a cross-store reference, the SID of the target principal could not be resolved. The error code is 1722.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[PrincipalOperationException: While trying to resolve a cross-store reference, the SID of the target principal could not be resolved. The error code is 1722.]
System.DirectoryServices.AccountManagement.ADStoreCtx.ResolveCrossStoreRefToPrincipal(Object o) +570
System.DirectoryServices.AccountManagement.ADUtils.DirectoryEntryAsPrincipal(DirectoryEntry de, ADStoreCtx storeCtx) +133
System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.get_CurrentAsPrincipal() +86
System.DirectoryServices.AccountManagement.PrincipalCollectionEnumerator.MoveNext() +252
System.DirectoryServices.AccountManagement.PrincipalCollectionEnumerator.System.Collections.IEnumerator.MoveNext() +9
System.Linq.<SelectManyIterator>d__22`3.MoveNext() +65
System.Linq.Lookup`2.Create(IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer) +264
System.Linq.GroupedEnumerable`3.GetEnumerator() +72
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +63
System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) +392
System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection) +15
Plastin.Common.Security.ADLDSClaimsProvider.SetApplicationClaims() +1012
Plastin.Common.Security.ADLDSClaimsProvider.Initialise() +174
Plastin.Common.Security.ADLDSClaimsProvider..cctor() +238
[TypeInitializationException: The type initializer for 'Plastin.Common.Security.ADLDSClaimsProvider' threw an exception.]
lambda_method(Closure , IBuilderContext ) +81
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +35
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +10
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +198
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +209
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +165
[ResolutionFailedException: Resolution of the dependency failed, type = "Plastin.Common.Security.IClaimsProvider", name = "(none)".
Exception occurred while: Calling constructor Plastin.Common.Security.ADLDSClaimsProvider().
Exception is: TypeInitializationException - The type initializer for 'Plastin.Common.Security.ADLDSClaimsProvider' threw an exception.
-----------------------------------------------
At the time of the exception, the container was:
Resolving Plastin.Common.Security.ADLDSClaimsProvider,(none) (mapped from Plastin.Common.Security.IClaimsProvider, (none))
Calling constructor Plastin.Common.Security.ADLDSClaimsProvider()
]
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +329
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) +15
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, ResolverOverride[] overrides) +72
Plastin.Common.Security.AuthenticationManager.Authenticate(String resourceName, ClaimsPrincipal incomingPrincipal) +149
Plastin.Portal.MvcApplication.Application_PostAuthenticateRequest() +70
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +87
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +21
System.Web.Util.ArglessEventHandlerProxy.Callback(Object sender, EventArgs e) +56
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +141
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
Finally we fixed this issue and my apologies I am getting late to answer this question. After lots of debugging we identified that our web application was throwing this error while getting members of ADLDS group. It was unusual as same application was working on other server. So we decided to captured network traffic using Wireshark. Wireshark capture indicated that connectivity between LDAP server and application server was blocked over SMB port 445. So we get our Network team to open port 445 which fixed the issue.
This error seems very generic error and could be other reasons for this error in your scenario but using network traffic capturing tool (like wireshark) at early stage of investigation might help you to troubleshoot these kind of issue quickly.

Self-hosted WCF 4.5 WsHttpBinding -> 400 Bad Response

I'm self-hosting a WCF WSHttpBinding bound service. When running, I can't get any variation on the service call to work. Can you diagnose this problem?
A basic GET from the address bar (multiple browsers) fails with 400 Bad Request. So does $.ajax with GET, POST with 'dataType': 'json' or 'dataType': 'jsonp'. I've tried variations on the base address. Including or omitting the WebInvokeAttribute doesn't make a difference. Whether or not the HTTP Method is matched or mismatched doesn't make a difference.
Setting the service endpoint to a narrower path and then browsing to paths outside of that endpoint appropriately results in an error (about the method not being allowed). Using GET from ajax without jsonp will fail due to cross-site-scripting protections as expected but I can avoid that scenario.
(There are a million versions of this question online. Some seem resolved, but with answers that don't help. Others are unresolved. This is not an exact duplicate of any of them.)
The WCF trace invariably indicates: "There is a problem with the XML that was received from the network." with "The body of the message cannot be read because it is empty" as the inner exception - even for a GET request for which there should be no body (right?). Even if I attempt to POST with json data of '' or '{}', I get still this error exactly.
This code sample is mostly from: http://msdn.microsoft.com/en-us/library/ms730935.aspx, a .Net 4.5 WCF sample. The sample is bigger than necessary and I had to add binding.HostNameComparisonMode = HostNameComparisonMode.Exact; so that Windows would allow it to run without full admin rights. I also played with the relative url (now empty) to test.
Running this and pointing the browser to http://localhost:8000/ is properly serving the MEX/WSDL advertisement. This tells me that the webservice is running and that I am browsing to the right endpoint (plus or minus a service prefix, at least) and that Windows Firewall or permissions are not interfering with the process's ability to open or serve on a port. Yet http://localhost:8000/Ping just gets 400.
If I remember correctly (maybe not though), older versions of WCF and .NET didn't allow or didn't support self-hosted web-like protocols. I believe that's changed. Again, the serving of the MEX data isn't all that different from the custom stuff I want to serve - it's just coming from a different place in the same process.
sdb.IncludeExceptionDetailInFaults = true; seems to have no helpful effect here.
using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
namespace WCFWebHost
{
static class Program
{
[STAThread]
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8000/");
ServiceHost selfHost = new ServiceHost(typeof(EchoService), baseAddress);
try
{
var binding = new WSHttpBinding();
binding.HostNameComparisonMode = HostNameComparisonMode.Exact;
selfHost.AddServiceEndpoint(typeof(IEcho), binding, "");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
var sdb = selfHost.Description.Behaviors.Find<ServiceDebugBehavior>();
sdb.IncludeExceptionDetailInFaults = true;
selfHost.Open();
Console.WriteLine("Open and waiting.");
Console.ReadKey(true);
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
}
}
[ServiceContract(Namespace = "http://echo")]
public interface IEcho
{
[OperationContract]
[WebInvoke(
Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "Ping")]
void Ping();
}
public class EchoService : IEcho
{
public void Ping()
{
}
}
}
The web config has this traces.svc configuration added:
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="System.ServiceModel"
switchValue="Verbose, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="C:\Users\...\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
===
Something that seems odd to me is that the traced exception seems to be coming from the error reporting itself. Is this error in the trace hiding better information about the original failure? Or am I just reading a re-throw wrong?
<Exception>
<ExceptionType>System.ServiceModel.ProtocolException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>There is a problem with the XML that was received from the network. See inner exception for more details.</Message>
<StackTrace>
at System.Runtime.Diagnostics.EtwDiagnosticTrace.WriteExceptionToTraceString(XmlTextWriter xml, Exception exception, Int32 remainingLength, Int32 remainingAllowedRecursionDepth)
at System.Runtime.Diagnostics.EtwDiagnosticTrace.ExceptionToTraceString(Exception exception, Int32 maxTraceStringLength)
at System.Runtime.Diagnostics.EtwDiagnosticTrace.GetSerializedPayload(Object source, TraceRecord traceRecord, Exception exception, Boolean getServiceReference)
at System.Runtime.TraceCore.ThrowingException(EtwDiagnosticTrace trace, String param0, String param1, Exception exception)
at System.Runtime.ExceptionTrace.TraceException[TException](TException exception, String eventSource)
at System.Runtime.ExceptionTrace.AsError(Exception exception)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.CompleteParseAndEnqueue(IAsyncResult result)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.HandleParseIncomingMessage(IAsyncResult result)
at System.Runtime.AsyncResult.SyncContinue(IAsyncResult result)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult..ctor(ReplyChannelAcceptor acceptor, Action dequeuedCallback, HttpPipeline pipeline, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginProcessInboundRequest(ReplyChannelAcceptor replyChannelAcceptor, Action dequeuedCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceivedAsyncResult`1.ProcessHttpContextAsync()
at System.ServiceModel.Channels.HttpChannelListener`1.BeginHttpContextReceived(HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.SharedHttpTransportManager.EnqueueContext(IAsyncResult listenerContextResult)
at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContextCore(IAsyncResult listenerContextResult)
at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContext(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.ListenerAsyncResult.IOCompleted(ListenerAsyncResult asyncResult, UInt32 errorCode, UInt32 numBytes)
at System.Net.ListenerAsyncResult.WaitCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</StackTrace>
<ExceptionString>System.ServiceModel.ProtocolException: There is a problem with the XML that was received from the network. See inner exception for more details. ---> System.Xml.XmlException: The body of the message cannot be read because it is empty.
--- End of inner exception stack trace ---</ExceptionString>
<InnerException>
<Exception>
<ExceptionType>System.Xml.XmlException, System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The body of the message cannot be read because it is empty.</Message>
<StackTrace>
at System.Runtime.Diagnostics.EtwDiagnosticTrace.WriteExceptionToTraceString(XmlTextWriter xml, Exception exception, Int32 remainingLength, Int32 remainingAllowedRecursionDepth)
at System.Runtime.Diagnostics.EtwDiagnosticTrace.GetInnerException(Exception exception, Int32 remainingLength, Int32 remainingAllowedRecursionDepth)
at System.Runtime.Diagnostics.EtwDiagnosticTrace.WriteExceptionToTraceString(XmlTextWriter xml, Exception exception, Int32 remainingLength, Int32 remainingAllowedRecursionDepth)
at System.Runtime.Diagnostics.EtwDiagnosticTrace.ExceptionToTraceString(Exception exception, Int32 maxTraceStringLength)
at System.Runtime.Diagnostics.EtwDiagnosticTrace.GetSerializedPayload(Object source, TraceRecord traceRecord, Exception exception, Boolean getServiceReference)
at System.Runtime.TraceCore.ThrowingException(EtwDiagnosticTrace trace, String param0, String param1, Exception exception)
at System.Runtime.ExceptionTrace.TraceException[TException](TException exception, String eventSource)
at System.Runtime.ExceptionTrace.AsError(Exception exception)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.CompleteParseAndEnqueue(IAsyncResult result)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.HandleParseIncomingMessage(IAsyncResult result)
at System.Runtime.AsyncResult.SyncContinue(IAsyncResult result)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult..ctor(ReplyChannelAcceptor acceptor, Action dequeuedCallback, HttpPipeline pipeline, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginProcessInboundRequest(ReplyChannelAcceptor replyChannelAcceptor, Action dequeuedCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceivedAsyncResult`1.ProcessHttpContextAsync()
at System.ServiceModel.Channels.HttpChannelListener`1.BeginHttpContextReceived(HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.SharedHttpTransportManager.EnqueueContext(IAsyncResult listenerContextResult)
at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContextCore(IAsyncResult listenerContextResult)
at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContext(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.ListenerAsyncResult.IOCompleted(ListenerAsyncResult asyncResult, UInt32 errorCode, UInt32 numBytes)
at System.Net.ListenerAsyncResult.WaitCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</StackTrace>
<ExceptionString>System.Xml.XmlException: The body of the message cannot be read because it is empty.</ExceptionString>
</Exception>
</InnerException>
</Exception>
WSHttpBinding creates a soap based binding. You cannot access this endpoint using a browser by navigating to the URL. You can access this binding by creating a service proxy or using wcftestclient (for testing). If you are looking for developing a REST endpoint then use webHttpBinding instead of wsHttpBinding.
Here is a quick sample on how to develop REST based service. Here is a post which describes the differences between webHttpBinding & wsHttpBinding.
Call WCF Service exposed with WSHttp binding
web.config Settings
<services>
<service name="MyWcfService.MyService">
<endpoint address="jh" binding="wsHttpBinding" bindingConfiguration="NoSecurity" contract="MyWcfService.IMyService" />
</service>
</services>
html page
//SOAP request generated in order to call the Service method
var whRequest ="<s:Envelope xmlns:a=\"http://www.w3.org/2005/08/addressing\" xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\">" +
"<s:Header>" +
"<a:Action s:mustUnderstand=\"1\">http://tempuri.org/IMyService/GetData</a:Action>" +
"<a:MessageID>urn:uuid:7fdde7b6-64c8-4402-9af1-cc848f15888f</a:MessageID>" +
"<a:ReplyTo>" +
"<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>" +
"</a:ReplyTo>" +
"<a:To s:mustUnderstand=\"1\">http://localhost:1415/MyService.svc/jh</a:To>" +
"</s:Header>" +
"<s:Body>" +
"<GetData xmlns=\"http://tempuri.org/\">"+
"<value>9</value>"+
"</GetData>" +
"</s:Body>" +
"</s:Envelope>";
$(document).ready(function () {
$("#btnWCFWSHttp").click(function () {
$.ajax({
type: "POST",
url: "http://localhost:1415/MyService.svc/jh/",
data: whRequest,
timeout: 10000,
contentType: "application/soap+xml",
dataType: "xml",
async: false,
success: function (data, status, xhr) {
$(data).find("GetDataResponse").each(function () {
alert($(this).find("GetDataResult").text());
});
},
error: function (xhr, status, error) {
alert(error);
}
});
});
});

How to catch exception/fault where message size is larger than accepted by the service (server side)?

At first, I thought if I added an implementation of IDispatchMessageInspector, that perhaps this would intercept the message size before any checking on the limit is done. I soon found, this is not the case. The running service obviously makes sure to enforce this rule on a lower level. Now I am curious if there is a way in which I can capture such an exception on the server level and return a response to the client. Would the an implementation of IErrorHandler as a ServiceBehavior do the trick?
Maybe the more general question is: Can this be tracked at the server level?
It may also be worth noting that I am not in control of the WSDL.
The message size is verified at the lower level - at the transport level.
There isn't a easy way to catch that exception (The IErrorHandling interface provided by WCF to handle exceptions doesn't work at this level).
One way would be to create your own custom wcf transport channel (see here an example)
See below how the generated exception looks like when the quota is exceeded - you can see that this is thrown from the low level (HttpChannelListener).
<ExceptionType>System.ServiceModel.ProtocolException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The maximum message size quota for incoming messages (225) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.</Message>
<StackTrace>
at System.ServiceModel.Channels.HttpInput.ThrowHttpProtocolException(String message, HttpStatusCode statusCode, String statusDescription)
at System.ServiceModel.Channels.HttpInput.ThrowMaxReceivedMessageSizeExceeded()
at System.ServiceModel.Channels.HttpInput.GetMessageBuffer()
at System.ServiceModel.Channels.HttpInput.ParseMessageAsyncResult.DecodeBufferedMessageAsync()
at System.ServiceModel.Channels.HttpInput.ParseMessageAsyncResult.BeginParse()
at System.ServiceModel.Channels.HttpInput.BeginParseIncomingMessage(HttpRequestMessage httpRequestMessage, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginParseIncomingMessage(AsyncCallback asynCallback, Object state)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult..ctor(ReplyChannelAcceptor acceptor, Action dequeuedCallback, HttpPipeline pipeline, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginProcessInboundRequest(ReplyChannelAcceptor replyChannelAcceptor, Action dequeuedCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceivedAsyncResult`1.ProcessHttpContextAsync()
at System.ServiceModel.Channels.HttpChannelListener`1.BeginHttpContextReceived(HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</StackTrace>
The best you can do (and the usual way of monitoring this) is to enable logging at the message level.
http://geekswithblogs.net/mnf/archive/2008/10/03/use-wcf-message-logging.aspx
the problem is that the maxMessageSize properties must be set on both client and server. So if the message is too large to be sent or received on the client side, your server will not know about this.

The I/O operation has been aborted because of either a thread exit or an application request

I'm running some WCF net.tcp services on a high-traffic website.
In my local environment everything worked as expect.
In the production environment, the website works for few minutes then the service throw an exception.
When I stop and start again the service website it works again for few minutes.
Here's the details:
A TCP error (995: The I/O operation has been aborted because of either a thread exit or an application request) occurred while transmitting data.
System.ServiceModel.Channels.SocketConnection.EndRead()
System.ServiceModel.Channels.TracingConnection.EndRead()
System.ServiceModel.Channels.ConnectionStream.ReadAsyncResult.OnAsyncReadComplete(Object state)
System.ServiceModel.Channels.TracingConnection.TracingConnectionState.ExecuteCallback()
System.ServiceModel.Channels.SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead)
System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
The I/O operation has been aborted because of either a thread exit or an application request
I see the same problem on Win8kR2SP1Web:
System.Runtime.InteropServices.COMException (0x800703E3): The I/O operation has been aborted because of either a thread exit or an application request. (Exception from HRESULT: 0x800703E3)
An error occurred while communicating with the remote host. The error code is 0x800703E3.
The I/O operation has been aborted because of either a thread exit or an application request. (Exception from HRESULT: 0x800703E3)
at System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32 result, Boolean throwOnDisconnect)
at System.Web.Hosting.IIS7WorkerRequest.ReadEntityCoreSync(Byte[] buffer, Int32 offset, Int32 size)
at System.Web.HttpRequest.GetEntireRawContent()
at System.Web.HttpRequest.FillInFormCollection()
at System.Web.HttpRequest.get_Form()
at System.Web.Mvc.HttpRequestExtensions.GetHttpMethodOverride(HttpRequestBase request)
at System.Web.Mvc.AcceptVerbsAttribute.IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
at System.Linq.Enumerable.All[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Web.Mvc.ActionMethodSelector.RunSelectionFilters(ControllerContext controllerContext, List`1 methodInfos)
at System.Web.Mvc.ReflectedControllerDescriptor.FindAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.ControllerActionInvoker.FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, String actionName)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.<EndProcessRequest>b__d()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionSt ep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
First time in 1 year though ...

Asynchronous WCF fails with MessageSecurityException when multiple worker processes (Web Garden)

I have a simple WCF service using ws2007HttpBinding which puts in a configurable delay, then returns. The service is configured to be PerCall. The service is hosted on IIS 7.5 on Windoes 2008 Server R2 SP1
I am call this asynchronously via console app using an imported service reference.
I can easily inject 10000 requests and they are all successful. Each request uses a new WCF proxy. The CPU was running about 70%
I wanted to see if adding another worker process would help throughput and utilise the full 100% cpu. I configured it to have 2 worker processes.
When I ran this it began to fail virtually immediately with a MessageSecurityException. Even if I set the number of requsts to 10, it still fails. I noticed that it fails more if the timer in the WCF service is short ( between 10 and 50 ms). A higher delay causes less failures.
It either fails on the proxy.Open() or proxy.Close()
I investigated this and thought it might be related to secure conversation. So I disabled this by
setting
establishSecurityContext="false"
(Is this correct?) I am confused why this would be the case if I am creating a new proxy each time
This dis not seem to make any difference.
When I return the AppPool to have only 1 worker process it works again
Has anybody had the same issue, and managed to get a solution. If so can you post you solution in explicit detail.
The errors received are as follows
In the WCF trace it reported
The incoming message is not part of an existing security session
The exception shown in trace
System.ServiceModel.EndpointNotFoundException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
There was no channel that could accept the message with action 'http://tempuri.org/ILoadedService/RunLoad'.
at System.ServiceModel.Dispatcher.ErrorBehavior.ThrowAndCatch(Exception e, Message message)
at System.ServiceModel.Channels.DatagramChannelDemuxer2.ProcessItem(TInnerItem item)
at System.ServiceModel.Channels.DatagramChannelDemuxer2.HandleReceiveResult(IAsyncResult result)
at System.ServiceModel.Channels.DatagramChannelDemuxer2.OnReceiveComplete(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.ServiceModel.Channels.ReplyChannel.HelpReceiveRequestAsyncResult.OnReceiveRequest(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.Runtime.InputQueue1.AsyncQueueReader.Set(Item item)
at System.Runtime.InputQueue1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)
at System.Runtime.InputQueue1.EnqueueAndDispatch(T item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
at System.ServiceModel.Channels.SingletonChannelAcceptor`3.Enqueue(QueueItemType item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
at System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback)
at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
System.ServiceModel.EndpointNotFoundException: There was no channel that could accept the message with action 'http://tempuri.org/ILoadedService/RunLoad'.
Exception caught on the client
Exception thrown of type [System.ServiceModel.Security.MessageSecurityException] Source [mscorlib]
Exception when receiving response [9] - Message [An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.] StackTrace [
Server stack trace:
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeEndService(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 SimpleIISTestClient.SlowClient.ILoadedService.EndRunLoad(IAsyncResult result)
at SimpleIISTestClient.Program.PerfAsynchCallback(IAsyncResult result) in C:\CRF Prototypes\Load\SimpleIISTestClient\Program.cs:line 116]
Inner Exception [9] - Message [The security context token is expired or is not valid. The message was not processed.] StackTrace []