[OWIN] ASP.NET 使用 Startup 類別

  • 7721
  • 0
  • 2016-07-28

Startup 類別是 OWIN 在啟動時,第一次會執行 Configuration 方法,

在這方法裡面就能使用 IAppBuilder 來建構各種應用的設定,

 在網站啟動後,Owin 的 SystemWeb 會去尋找網站專案命名空間下的為 Startup 類別名稱,且有個方法叫做 Configuration,

namespace SingalRSample
{
	public partial class Startup
	{
		public void Configuration(IAppBuilder app)
		{
			
		}
	}
}

接著會執行 Configuration 這個方法,這個說法是從 Call Stack 看來的,

如果將 Startup 類別定義在非專案命名空間下的其他命名空間,是沒有效果的,且會拋出例外錯誤,

例如將命名空間改為 namespace SingalRSample.ABC,執行網站後,就會看到以下錯誤

The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No 'Configuration' method was found in class 'SingalRSample.Startup, SingalRSample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.

從錯誤訊息當中,也提示我們有兩種方法能讓 SystemWeb 辨識出 Startup,

第一種是要定義 OwinStartupAttribute,例如 [assembly: OwinStartupAttribute(typeof(SingalRSample.ABC.Startup))]

第二種就是按照他說的需要將 Startup 放在 SingalRSample 命名空間下(SingalRSample 這只是我測試網站的命名空間,請勿以為要取一樣的)

 

所以透過 OwinStartupAttribute,也可以自由定義類別名稱,只要也有 Configuration 方法就行,不一定要叫做 Startup 的,

但個人覺得按照習慣來配置會比較好,所以我還是會使用 Startup 在預設的專案命名空間下,這樣讓不同人看到專案時,也好理解。