【问题标题】:Read AssemblyTitle attribute in ASP.NET在 ASP.NET 中读取 AssemblyTitle 属性
【发布时间】:2011-09-06 12:40:03
【问题描述】:

我使用下面的代码来读取 .NET 应用程序的 AssemblyTitle 属性,不幸的是,Assembly.GetEntryAssembly() 在 ASP.NET 应用程序中总是返回 Null。如何在 ASP.NET 应用程序中读取 AssemblyTitle?

  public static string Title
  {
      get
      {
          var attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
          if (attributes.Length > 0)
          {
              var titleAttribute = (AssemblyTitleAttribute)attributes[0];
              if (titleAttribute.Title.Length > 0)
                  return titleAttribute.Title;
          }
          return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().CodeBase);
      }
  }

【问题讨论】:

  • 使用你的代码 (codekeep.net/snippets/170dc91f-1077-4c7f-ab05-8f82b9d1b682.aspx) 我总能得到程序集标题:i.stack.imgur.com/b7qGQ.png 那你在做什么?您在哪里运行该代码?
  • @Balexandre 尝试从 IIS7 上托管的 ASP.NET 应用程序执行代码
  • 我将它托管在 IIS 7.5 Express 上并且工作正常。
  • 注意:假设它是第一个属性 (attribute[0]) 并不是那么好。这部分可以用更安全的方式写成:assembly.GetCustomAttributes()?.Where(x => x is AssemblyTitleAttribute).Select(x => ((AssemblyTitleAttribute) x).Title).FirstOrDefault(x => !string.IsNullOrWhiteSpace(x));

标签: asp.net reflection .net-assembly


【解决方案1】:

您必须有一个您知道在包含AssemblyTitle 的程序集中定义的类型。然后你可以这样做:

typeof(MyType).Assembly.GetCustomAttributes

请注意(据我所知)没有任何其他防弹方法。

例如,如果您不想在 Web 请求期间使用 HttpContext.Current 将不起作用(因此您可以根据用户操作的响应来执行此操作,但不能来自单独的线程或静态初始化程序,或来自global.asax)

一些类似的读物(成功一半):

GetEntryAssembly for web applications

Using the Web Application version number from an assembly (ASP.NET/C#)

【讨论】:

    【解决方案2】:

    我在 asp.net 网络应用程序中使用以下内容:

    if (ApplicationDeployment.IsNetworkDeployed)
        return ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
    return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
    

    编辑:对不起,这只是版本,不是标题!我结合了你的版本和我的版本:

    System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); 
    

    这样就可以很好地获取程序集标题属性。区别在于GetExecutingAssembly() 与您的GetEntryAssembly()

    【讨论】:

    • Assembly.GetExecutingAssembly() 的问题在于,如果代码在类库中并在 ASP.NET 中引用,则标题将始终来自类库而不是 ASP.NET 应用程序。
    猜你喜欢
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2011-11-10
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多