Randomly getting 'System.BadImageFormatException: Index not found' error in Web API after some deployments to an Azure App Service

The exception that is thrown when the file image of a dynamic link library (DLL) or an executable program is invalid. If you get a BadImageFormatException when interfacing with a native DLL, it almost always means that you are trying to interface with a 32-bit DLL while running in the 64-bit CLR, or vice versa. In most cases you might be facing the problem with your website after deploying on server.

Make sure that you are not having 32-bit / 64-bit conflict. So, you need to adjust your application pool to Enable 32-Bit or 64-Bit accordingly. Set the Target platform setting on your c# EXE project, not your class library project. Alternatively, you can ship both 32-bit and 64-bit DLLs with different file names, define separate P/Invoke stubs for each version, and decide which one to call at runtime. The easiest way to do this would probably be to wrap your native calls in an interface (e.g., INativeMethods) and choose which implementation to instantiate at runtime based on IntPtr.Size. With this method, you could still target AnyCPU.