Search code examples
c#dynamics-crmmicrosoft-dynamicsmethodaccessexception

MethodAccessException: Attempt by method X to access method Y failed in Dynamics 365 Plugin On Prem


I'm getting the error below when trying to move a plugin from version .NET version 4.5.2 to 4.6.2 in Dynamics 365 v9.1

 System.AggregateException: One or more errors occurred. ---> System.MethodAccessException: Attempt by method 'System.Net.Http.WinHttpResponseParser.GetReasonPhrase(System.Net.HttpStatusCode, Char[], Int32)' to access method 'System.Net.HttpStatusDescription.Get(System.Net.HttpStatusCode)' failed.
   at System.Net.Http.WinHttpResponseParser.GetReasonPhrase(HttpStatusCode statusCode, Char[] buffer, Int32 bufferLength)
   at System.Net.Http.WinHttpResponseParser.CreateResponseMessage(WinHttpRequestState state, Boolean doManualDecompressionCheck)
   at System.Net.Http.WinHttpHandler.<StartRequest>d__103.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.Http.HttpClient.<FinishSendAsync>d__58.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)

I can deploy the plugin and it works fine. I'm getting the error above when the plugin attempts to make a web service call to an external API we call from the plugin

The plugin is NOT in sandbox mode and it's registered in the database enter image description here

I opened the plugin assembly with JustDecompile and tracked down the issue to loading a method in System.dll, it looks like it's trying to load it from the GAC and fails.

enter image description here

Anyone had the same issue? This same plugin works in .NET 4.5.2 but fails in 4.6.2


Solution

  • We managed to find a solution for this, the problem was ILMerge was including all System.*.dll, reading in this stackoverflow answer https://stackoverflow.com/a/67334636/2059998

    You might want to avoid merging anything that's part of the .NET Framework (which I assume that libraries like System.Memory and System.Threading.Tasks are).

    So adding the line <Files Remove="$(TargetDir)System*.dll" /> for ILMerge in the .NET project file fixed the issue, this makes sure the files are not included when running ILMerge

    <Target Name="ILMerge" AfterTargets="Build">
    <ItemGroup>
        <Files Include="$(TargetDir)*.dll" />
        <Files Remove="$(TargetDir)$(AssemblyName).dll" /> 
        <Files Remove="$(TargetDir)AntiXSSLibrary.dll" />
        <Files Remove="$(TargetDir)Microsoft*.dll" />
        <Files Remove="$(TargetDir)System*.dll" />
    </ItemGroup>