ASP.NET Core 应用程序可以通过内部进程托管或外部进程托管来运行。在内部进程托管模式下,应用程序直接运行在 IIS 或 Kestrel 服务器进程中,而在外部进程托管模式下,应用程序则需要通过外部服务器(如 nginx)来启动和运行。
外部进程托管模式的优点是可以帮助应用程序处理大量的并发请求和负载均衡。同时,如果应用程序需要在 Linux 环境下运行,它也必须采用外部进程托管模式。
以下是如何使用 nginx 作为外部服务器来托管 ASP.NET Core 应用程序的示例:
Microsoft.AspNetCore.Server.Kestrel
Microsoft.AspNetCore.Server.Nginx
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseNginx()
.UseStartup();
此代码将使用 Kestrel 和 Nginx 服务器托管 ASP.NET Core 应用程序,并将启动类指定为 Startup。
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
此代码将配置 nginx 代理到 ASP.NET Core 应用程序的 Kestrel 服务器,可以通过访问 http://localhost 来访问应用程序。
需要注意的是,如果要使应用程序在 Linux