How can I get the web application assembly in ASP.NET without Global.asax?

I want to dynamically get the assembly for the currently executing web application from any code referenced by that application and executed in the same AppDomain.

I want exactly what this question asks: Get web application assembly name, regardless of current executing assembly

However, all replies in that question use the Global.asax file to get the web app assembly. That doesn't work if the application doesn't have a global.asax file, since in this case the type returned is HttpApplication , which is in the System.Web assembly.

One way I thought about going is to filter the assemblies in the current AppDomain by something, but I don't know what this something could be. Is there any difference between the assembly of the web app and another normal DLL? I know that the projects in Visual Studio have a GUID to signify the type of project (ASP.NET Web App, class library, MVC app, etc.) Is this info somehow present in the compiled assembly?

Another approach could be to use the ApplicationHost from the System.Web.Hosting namespace, but that only has static data and nothing about assemblies.

A third approach would be to include a type in the web app project and use that type, but for that my code which needs to get the web assembly name needs a reference to that type (and that would be a circular reference).

Any ideas?


As a very ugly hack, you could find an ASPX file in the app, then get the assembly containing its compiled type:

var filePath = Directory.EnumerateFiles(HttpRuntime.AppDomainAppPath, "*.aspx")
                        .FirstOrDefault();
var assembly = BuildManger.GetCompiledType(filePath).Assembly;

If there aren't any ASPX files, you could try ASHX or ASMX or CSHTML.

This will not work correctly for a web site project, where each file gets its own assembly.

链接地址: http://www.djcxy.com/p/23718.html

上一篇: 全球资源在c#中的最佳实践

下一篇: 如何在没有Global.asax的ASP.NET中获得Web应用程序程序集?