You may come across this error message while trying to use a third-party library in your .NET application: “Cannot perform CAS Asserts”. As the message implies, this issue is about the security mechanism that protects your system from unreliable components.
Here is the entire error message:
System.InvalidOperationException: Cannot perform CAS Asserts in Security Transparent methods
What is CAS (Code Access Security)?
CAS is a security mechanism provided by .NET Framework to protect your system against malicious code blocks and components.
The .NET Framework provides a mechanism for the enforcement of varying levels of trust on different code running in the same application called Code Access Security (CAS).Microsott Docs
Why we need CAS?
Users obtain code from many sources, some of which might be unreliable; code can contain bugs or vulnerabilities that enable it to be exploited by malicious code; and code sometimes does things that the user does not know it will do. As a result, computer systems can be damaged and private data can be leaked when cautious and trustworthy users run malicious or error-filled software.Microsott Docs
The reason you receive “Cannot perform CAS Asserts” error is that your application is trying to use an external library that is not trusted by CAS. It happens especially when you upgrade .NET Framework version in your development machine. In this case, you should update your code as per the new CAS requirements come with the new .NET Framework version.
For more information about major CAS changes in .NET Framework 4.0: Link 1, link 2
Receiving Schannel 10013 error? Check this post out.
How to solve “Cannot perform CAS Asserts” error
Solution 1: Full-trust
Making your application a “full-trust” application solves this issue unless the application is marked as security-transparent. However, many hosting companies don’t allow applications run on “full-trust”.
Solution 2: GAC
Another way to solve this issue is that adding the external DLLs into GAC (Global Assembly Cache) by using Gacutil.exe. Check this article out for instructions to install an assembly into GAC. Gacutil.exe comes with Windows SDK and Visual Studio.
Solution 3: Code changes
Changing your application’s code and making it compatible with the new CAS implementations is the best solution in the long-term. Here is an article to guide you through the changes you should make in your code.