Search code examples
c#.netasp.net-corewebclient.net-assembly

How to load a DLL file from a specific URL in Asp.Net Core


I would like to download a DLL file from http://localhost:8080/bin/ and instantiate classes and functions in my Asp.Net Core application.

I've made a little console application (in .NET Framwork) doing this. Here the code :

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var wc = new WebClient())
            {
                var myDll = Assembly.Load(wc.DownloadData("http://localhost:8080/test-dll/bin/myDll.dll"));

                Type t = myDll .GetType("ConsoleApplication1.Test");


                // Instantiate my class

                object myObject = new object();
                myObject = Activator.CreateInstance(t);
            }
        }
    }
}

Unfortunately, WebClient is not supported in .Net Core.

So, how can I load a dll file located in a specific URL and instantiate it ? (in .Net Core)

Thanks in advance for your answers !


Solution

  • You should be able to download file in ASP.Net core using following code.

    using (HttpClient client = new HttpClient())
            {
                string url = "http://localhost:55272/myDll.dll";
                using (var response = await client.GetAsync(url))
                {
                    response.EnsureSuccessStatusCode();
    
                    using (var inputStream = await response.Content.ReadAsStreamAsync())
                    {
                        var mydll = AssemblyLoadContext.Default.LoadFromStream(inputStream);
    
                    }
                }
            }
    

    But remember that certain file types such as .config, .dll .exe are protected in IIS and you will not be able to download such files with default settings/configuration of IIS. You need to configure that part explicitly. May be this link can be helpful on that front.