编程语言
首页 > 编程语言> > c#-在网站中使用反射访问AssemblyInfo.cs中的信息

c#-在网站中使用反射访问AssemblyInfo.cs中的信息

作者:互联网

我创建了一个DLL,它将从AssemblyInfo.cs中收集信息.在类构造函数中,我使用Reflection来获取正在运行的最高级应用程序.

public class AppInfo()
{
    public AppInfo()
    {
        System.Reflection.Assembly assembly =
            System.Reflection.Assembly.GetEntryAssembly();
        if (assembly == null)
            assembly = System.Reflection.Assembly.GetCallingAssembly();


        //code to gather needed information
    }
}

如果我从给定应用程序MyApp中的任何DLL调用此函数,可以说该名称将始终为“ MyApp”.检索该信息不是问题,它在Windows服务和Windows应用程序中都很好用.我的问题是这样的:
如何获得最顶级网站的大会?

我找到了几篇文章,并且可以通过将网站的AssemblyInfo.cs从App_Code文件夹移到网站的根目录中,来在Global.asax.cs中获取信息.然后通过在AssemblyInfo.cs的物理路径中添加一个editor选项

<compiler
language="c#;cs;csharp"
extension=".cs"
compilerOptions="C:\Sandbox\MyWebSite\AssemblyInfo.cs"
type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">

使用它,我可以通过System.Reflection.Assembly.GetExecutingAssembly()在网站的AssemblyInfo.cs中检索信息.现在,我可以重载AppInfo类的构造函数以接受程序集并以这种方式检索信息,但是如果MyWebSite使用的另一个DLL创建了新的AppInfo(),我将获得该DLL的程序集信息,而不是父网站.

我知道,如果我使用的是Web Apps而不是Web站点,则不会出现此问题,但是由于某些原因,我将不进行介绍,因此无法使用Web Apps.无论我处于哪个DLL中,如何从正在运行的网站的AssemblyInfo.cs中读取信息,是否有任何建议?

编辑:我需要它才能用于网站,Windows应用程序和Windows服务

解决方法:

如果我正确理解您的问题,那么问题是Assembly.GetEntryAssembly()在网站中返回null,而Assembly.GetCallingAssembly()返回错误的消息,因为您有一系列调用,导致该网站不是直接调用方.如果是这样,您可以使用堆栈跟踪&找到“条目集”.往回走动.该堆栈将充满来自System.Web等的引用,因为该调用将源自IIS中某个地方的深处,但是您应该能够通过抓住可以肯定地确定的最低帧来挑选出您感兴趣的程序集属于你.请注意,这确实很hacky,但我认为它将为您提供所需的东西…

var trace = new StackTrace();
Assembly entryAssembly = null;
foreach (var frame in trace.GetFrames())
{
   var assembly = frame.GetMethod().DeclaringType.Assembly;
   //check if the assembly is one you own & therefore could be your logical
   //"entry assembly". You could do this by checking the prefix of the
   //Assembly Name if you use some standardised naming convention, or perhaps
   //looking at the AssemblyCompanyAttribute, etc
   if ("assembly is one of mine")
   {
      entryAssembly = assembly;
   }
}

希望其他人能够提出一种不太讨厌的方法……但是,如果您真的被困住了,这可能会有所帮助.

标签:reflection,web,assemblies,asp-net,c
来源: https://codeday.me/bug/20191107/2004061.html