Asp.net-Core
在 dotnet.exe 下執行時,IServerAddressesFeature 地址為空
我有一個 ASP.NET Core 2.0 Web 應用程序,我需要在啟動期間將應用程序的 URL 傳遞出去,以便與其他東西集成。
在 Visual Studio (IIS Express) 下執行時,
IApplicationBuilder.ServerFeatures.Get<IServerAddressesFeature>().Addresses包含我的應用程序綁定到的 URL(例如http://localhost:1234)。當執行 using
dotnet.exe myapp.dll時,同一個集合是空的,但是,我在 stdout 上得到一行說Now listening on: http://localhost:5000.問題是,要獲取 URL,我是否必須解析 dotnet.exe 的輸出以獲取行首
Now listening on:,還是有不那麼脆弱的方法?
這是由於 2017 年 3 月對 Kestrel 所做的更改。從公告中:
當沒有明確配置地址時,託管不再添加預設伺服器地址
當沒有指定時,WebHost
http://localhost:5000將不再添加預設伺服器地址。IServerAddressesFeature預設伺服器地址的配置現在將由伺服器負責。當沒有直接指定顯式地址時,指定的地址
IServerAddressesFeature旨在由伺服器用作備份。在沒有明確配置地址時,主機不再添加預設伺服器地址中有一個如何處理此問題的範例:
如果您正在實現伺服器並依賴於
IServerAddressesFeature通過託管設置,則將不再設置,並且在未配置地址時應添加預設值。舉個例子:var serverFeatures = featureCollection.Get<IServerAddressesFeature>(); if (serverFeatures .Addresses.Count == 0) { ListenOn(DefaultAddress); // Start the server on the default address serverFeatures.Addresses.Add(DefaultAddress) // Add the default address to the IServerAddressesFeature }