Is it possible to reference .net framework 4.7.2 class library from an ASP.NET Core MVC project?

后端 未结 2 2108
刺人心
刺人心 2020-12-30 16:10

I have an ASP.NET MVC 5 project which works well and it also references a .NET Framework 4.7.2 Class library which produces some CrystalReports. CrystalReports does not supp

2条回答
  •  孤城傲影
    2020-12-30 17:01

    Chris has already provided an excellent and accurate answer but I'll try to add a bit more color by sharing the results of an experiment I did.

    Experiment: I have a web application targerting .Net Core 3.1. It calls a library that targets the Full Framework. In that library I specifically make a call to a Full Framework API that is not available in .Net Core 3.1, in this case that type is SHA512Cng.

    My library code is:

            /// 
            /// Returns a base64 encoded Sha512 hash of the text specified.
            /// Uses the SHA512Cng implementation to do the hashing.
            /// 
            /// 
            /// 
            public static string Sha512Hash(string text) {
    
                using (SHA512Cng sha512Cng = new SHA512Cng()) {
                    byte[] bytes = Encoding.ASCII.GetBytes(text);
                    byte[] hashButes = sha512Cng.ComputeHash(bytes);
                    return Convert.ToBase64String(hashButes);
                }
            }
    

    In the home controller of my web application I make a call to use that Library method like so:

           public IActionResult Index() {
                string hash = App.Lib.Sha512Hash("hello world");
    
                return View();
            }
    

    Pretty simple experiment. This code is running on a windows machine that has the full framework installed. If I call this library from a website targeting the Full Framework it works perfectly.

    When I call this method in the Library from a .Net Core 3.1 website, what happens? That's the questions I wanted this experiment to answer.

    And the answer is...

    It throws the following exception:

    System.TypeLoadException: 'Could not load type 'System.Security.Cryptography.SHA512Cng' from assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.'

    Screenshot:

    So the takeaway is this: It really doesn't matter whether your code is running on a box with the Full Framework or not. If you reference a Full Framework Library from a website targeting Asp.Net Core 3 and make a call into a method that references a type that is incompatible with Asp.Net Core 3, then it's gonna throw.

提交回复
热议问题