Skip to content

XmlNamespaceManager corruption #743

Closed

Description

@andersjonsson

When testing things on our servers I got this exception:

System.InvalidOperationException: Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.
   at System.Collections.Generic.Dictionary<TKey,TValue>.FindValue(TKey key)
   at System.Collections.Generic.Dictionary<TKey,TValue>.TryGetValue(TKey key, TValue& value)
   at System.Xml.XmlNamespaceManager.LookupNamespaceDecl(String prefix)
   at System.Xml.XmlNamespaceManager.LookupNamespace(String prefix)
   at System.Xml.XmlNamespaceManager.LookupPrefix(String uri)
   at SoapCore.Namespaces.AddNamespaceIfNotAlreadyPresentAndGetPrefix(XmlNamespaceManager xmlNamespaceManager, String preferredPrefix, String uri)
   at SoapCore.Namespaces.AddDefaultNamespaces(XmlNamespaceManager xmlNamespaceManager)
   at SoapCore.SoapEndpointMiddleware<T>.GetXmlNamespaceManager()
   at SoapCore.SoapEndpointMiddleware<T>.ProcessMeta(HttpContext httpContext)
   at SoapCore.SoapEndpointMiddleware<T>.Invoke(HttpContext httpContext, IServiceProvider serviceProvider)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at legaonline.apiws.Startup.<>c.<<Configure>b__4_0>d.MoveNext() in Startup.cs:line 112
--- End of stack trace from previous location ---
   at StackExchange.Exceptional.ExceptionalMiddleware.Invoke(HttpContext context)

I see that this kind of error has been encountered before and that a PR has been merged #693 but obviously it can still happen, if multiple people access the endpoint before the XmlNamespaceManager has been fully populated

Activity

  1. JonRobidus commented on Jul 17, 2025

    @JonRobidus
    Contributor

    And when this happens the current middleware is corrupt and every Soap endpoint call throws an error.
    That is what we have seen in our project :(
    Not something you should accept... I think...

    XmlNamespaceManager is not threadsafe. So do not change the same instance in different requests.

    Caching XmlNamespaceManager's in the middleware (=singleton!) and mutating it within a request causes these thread safety issues.

  2. JonRobidus commented on Jul 17, 2025

    @JonRobidus
    Contributor

    My workaround:

    /// <summary>
    /// Fixes a thread safety issue in SoapCore. 
    /// SoapCore can mutate XmlNamespaceManager instances over multiple request when the first call is not finisched yet. This can lead to corrupted SoapCoreMiddleware.
    /// This cause errors for all subsequent requests to the same endpoint. 
    /// See issue: https://github.com/DigDes/SoapCore/issues/743
    /// </summary>
    public class AlwaysAwaitFirstCallToSoapEndpointMiddleware(RequestDelegate next)
    {
        private bool hasFirstRequestCompleted;
        private readonly SemaphoreSlim semaphore = new(1, 1);
    
        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Path.ToString().Contains("/SOAP/"))
            {
                if (!hasFirstRequestCompleted)
                {
                    await semaphore.WaitAsync();
                    try
                    {
                        if (!hasFirstRequestCompleted)
                        {
                            await next(context);
                            hasFirstRequestCompleted = true;
                            return;
                        }
                    }
                    finally
                    {
                        semaphore.Release();
                    }
                }
            }
            await next(context);
        }
    }
    
  3. JonRobidus commented on Jul 18, 2025

    @JonRobidus
    Contributor

    See PR #1146
    for the fix of this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions