如何在IIS上部署Angular和.NET Core Web API?

Tiy*_*ebM 5 asp.net iis asp.net-web-api asp.net-core-webapi angular

我们在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...
Run Code Online (Sandbox Code Playgroud)

为什么它在其他端口而不是相关的51975上监听?

为什么从Angular到API的连接被拒绝?

为什么关闭应用程序?

这是正确的方法吗?

更新1

在服务器上,应用程序可以正常运行,并具有以下配置:

  1. Angular在10.xyz:4200上,

  2. API 10.xyz:51975,

问题是,当我尝试使用公共ip或主机名时,我仍然只能访问angular而不是Web API,我试图为api分配主机名,但它还无法正常工作!

更新2

我还允许在我的主机名域上同时使用端口4200和51975。

更新3

我将Web API托管在IIS上,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
Run Code Online (Sandbox Code Playgroud)

关于CORS,这是我的配置,在本地运行良好:

 //In ConfigureServices method
 services.AddCors();

 //In Configure method
 app.UseCors(options => options.WithOrigins("http://localhost:4200/").AllowAnyMethod().AllowAnyHeader());
Run Code Online (Sandbox Code Playgroud)

谢谢

Ale*_*esD 5

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());
Run Code Online (Sandbox Code Playgroud)

您只需要对 Angular 客户端地址进行 CORS 设置,因为 Angular 应用程序需要获得权限才能向您的 Web API 发出 CORS 请求。它从公共地址调用,因此localhost配置无济于事,这仅在您使用 localhost 在本地访问它时有所帮助。

这里是关于 CORSAngular 文档Microsoft 文档如何启用 CORS 的链接,其中详细描述了它。