2011-09-06 67 views
1

我使用下面的代碼來閱讀.NET應用程序的AssemblyTitle屬性,不幸的是Assembly.GetEntryAssembly()總是在ASP.NET應用程序中返回Null。如何閱讀ASP.NET應用程序中的AssemblyTitle?閱讀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); 
     } 
    } 
+0

使用你的代碼(http://www.codekeep.net/snippets/170dc91f-1077- 4 c7f-ab05-8f82b9d1b682.aspx)我總是可以得到大會標題:http://i.stack.imgur.com/b7qGQ.png你在做什麼呢?你在運行那個代碼嗎? – balexandre

+0

@Balexandre嘗試從IIS7上託管的ASP.NET應用程序執行代碼 – Tomas

+0

我在** IIS 7.5 Express **上託管它,並且正常工作。 – balexandre

回答

4

您必須知道在包含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 web應用程序如下:

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()

+0

Assembly.GetExecutingAssembly()的問題在於,如果代碼位於類庫中並在ASP.NET中引用,則標題將始終來自類庫,而不是來自ASP.NET應用程序。 – Tomas