如何在 IIS 上部署 Angular 和 .NET Core Web API?
我們在 IIS 上為 angular_client 和 web_api 提供了兩個網站,安裝了託管捆綁包,並且已經授予了 IUSR、網路、網路服務和每個人等使用者的權限。
導航到每個站點單獨工作,即在 API 中,呼叫http://localhost:51975/api/user會生成所有使用者的列表。
問題是 Angular 登錄頁面無法與 API 通信以驗證使用者:
OPTIONS http://localhost:51975/api/user/authenticate net::ERR_CONNECTION_REFUSED我嘗試將與 API 關聯的 IP 修改為靜態 IP,即 10.1.xy,然後告訴 angular 改為呼叫http://10.1.xy:51975/api/user/authenticate。
在 API 中,我啟用了將日誌發送到瀏覽器以及日誌文件夾,它顯示的唯一日誌是:
Hosting environment: Production Content root path: C:\inetpub\wwwroot\api Now listening on: http://127.0.0.1:39834 Application started. Press Ctrl+C to shut down. Application is shutting down...為什麼它正在偵聽其他埠而不是關聯的一個 51975?
為什麼拒絕從 Angular 到 API 的連接?
為什麼應用程序正在關閉?
這是正確的方法嗎?
更新 1
僅在伺服器上,應用程序工作正常,具有以下配置:
- Angular 在 10.xyz:4200,
- API 10.xyz:51975,
問題是當我嘗試使用公共 ip 或我的主機名時,我仍然只能訪問 angular 而不能訪問 Web API,我試圖為 api 分配主機名,但它還沒有工作!
更新 2
我還允許我的主機名域上的埠 4200 和 51975。
更新 3
我在 IIS 上託管 Web API,API 和 Angular 都在同一台伺服器上,但網站不同。
我刪除了關於 CORS 已修復的聲明,因為我在瀏覽器控制台上仍然有警告,這是錯誤:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://{public IP}:51975/api/user/authenticate. (Reason: CORS request did not succeed).[Learn More] Object { headers: {…}, status: 0, statusText: "Unknown Error", url: "http://{public IP}:51975/api/user/authenticate", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://{public IP}:51975/api/user/authenticate: 0 Unknown Error", error: error } OPTIONS Http failure response for http://{public IP}:51975/api/user/authenticate net::ERR_CONNECTION_TIMED_OUT關於 CORS,這是我的配置,它在本地執行良好:
//In ConfigureServices method services.AddCors(); //In Configure method app.UseCors(options => options.WithOrigins("http://localhost:4200/").AllowAnyMethod().AllowAnyHeader());謝謝
CORS 錯誤解釋了您需要知道的一切。如果您還使用通過 DNS 名稱訪問,則還需要為公共 IP 和 DNS 配置 CORS。它必須配置為與您用於訪問 Angular 應用程序完全相同的 URL。
app.UseCors(options => options.WithOrigins( "http://localhost:4200/", "http://{public IP}:{public port}/", "http://{public DNS name}:{public port}/" ).AllowAnyMethod().AllowAnyHeader());您只需要對 Angular 客戶端地址進行 CORS 設置,因為 Angular 應用程序需要獲得向您的 Web API 發出 CORS 請求的權限。它從公共地址呼叫,因此
localhost配置無濟於事,僅當您使用 localhost 在本地訪問它時才有幫助。以下是有關 CORS 的 Angular 文件的連結以及Microsoft 文件如何啟用 CORS,其中詳細描述了它。