[Abastract]

When you open web form aspx source in VS2015, you may get two compilation errors for each aspx:

  • The type 'Global' is defined in an assembly that is not referenced. You must add a reference to assembly 'App_Code.****, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
  • Cannot convert type 'System.Web.HttpApplication' to 'ASP.global_asax'

I found that the code-behind Global.asx.cs is the cause and moving Global.asax.cs logic to Global.asax as inline code can solve the problem. After reporting to Microsoft Connect and getting feedback from support team, I found it is more like a bug of Productivity Power Tools 2015. Reported again.

【問題說明】

Visuals Studio 2015開啟舊Web Form專案,發現奇怪現象,原本專案可以正確編譯,但開啟幾個Web Form ASPX編輯後,網頁功能正常,但每個開啟的ASPX會出現兩個Global.asax相關編譯錯誤:

  • The type 'Global' is defined in an assembly that is not referenced. You must add a reference to assembly 'App_Code.****, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
  • Cannot convert type 'System.Web.HttpApplication' to 'ASP.global_asax'

歸納並爬文後發現,這有點像VS2015的Bug-只要在VS2015開啟編輯WebForm/ASPX,就可能發生以上問題。再做了一些對照實驗,理出一些結論,會不會發生問題跟Global.asax的寫法有關。我弄了一個小專案重現問題:

VS2015開啟Web Site,原本可以正常編譯。

 

開啟Default.aspx,VS2015顯示Default.aspx有CS0012跟CS0030編譯錯誤,但專案編譯跟執行都正常。

問題關鍵在於Global.asax的寫法,舊專案的Global.asax使用Code Behind,程式邏輯寫在App_Code\Global.asax.cs。而新Web Site專案範本預設是直接寫在Global.asax內。將Global.asax.cs的內容搬到Global.asax裡,問題消失!

調整Global.asax改成Inline寫法可以避免這個問題,但如果Global.asax需要使用動用繼承、實做介面等進階技巧時,Code Behind是唯一選擇(延伸閱讀),故這不算完整解決方案。

將問題回報到Microsoft Connect,很快得到微軟Support回覆,建議我改用安全模式測試,對照後才發現問題出在Productivity Power Tools 2015,停用問題便會消失。身為一名盡責的使用者,立刻再將狀況回報到Productivity Power Tools官網,剩下來就靜待修正囉~


Comments

# by wellxion

不是從aspx搬到aspx.cs就好?.?

# by Sam

黑暗大我有遇到類似的問題(VS2015),如果我在 UserControl (.ascx) Inherits 一個類別: public class TestAscx : System.Web.UI.UserControl ,則Register此ascx來使用的頁面,其方法也會出現紅色底線 錯誤 CS0012 類型 'XXXX' 定義在未參考的組件中。您必須加入組件 'App_Code.XXXX, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' 的參考。 但執行卻是正常,不知黑暗大大是否有解決方式?

# by Jeffrey

to Sam, 感覺跟這個案例的問題根源不太相同(可藉由停用Power Tools驗證),能否做一個小專案重現問題,這樣比較容易調查?(有時甚至在重現過程不知不覺就破案了)

# by Sam

是的~我有依黑暗大的方法做小專案重現問題,發現在.ascx 中的宣告為 <%@ Control Language="C#" ClassName="ascxSetting" Inherits="BaseAscx" %>, 其中BaseAscx為位在App_Code中的類別,沒有另外設定CodeFile的位置時,就會產生引用此控項方法會出現紅底的問題,這在前版不會出現,而且似乎c#才會如此,不知是否這樣的寫法不正式,但執行卻是正常的,這樣看又很像是bug。

# by Jeffrey

to Sam, 依你說的做法,測試停用Power Tools或不要開啟ascx編輯就不會出現紅蚯蚓,推測是Power Tools的問題。

# by Sam

to 黑暗大,因為我沒裝 Power Tools等額外套件,所以應該也不是此原因造成,我有擷圖如下,如大大有空可以試看看,圖1為錯誤頁面: https://goo.gl/CkO8xb https://goo.gl/RwAo0s https://goo.gl/DfTZE1

# by Jeffrey

to Sam, 看懂了,所以你並不是用Code Behind,而是將UserControl的Server端邏輯變成獨立類別放在App_Code中編譯。我覺得這屬於Visual Studio沒考量到的情境,將BaseAscx.cs搬到獨立DLL就可以克服問題。

Post a comment