ASP.NET Core基础之Main方法讲解
作者:痕迹g 时间:2024-06-05 15:43:21
为什么ASP.NET Core采用Main方法?
需要记住的最重要的一点是,ASP.NET Core Web 应用程序最初作为控制台应用程序启动,Main() 方法是应用程序的入口点。因此,当我们执行ASP.NET Core Web应用程序时,首先它寻找 Main() 方法,这是执行开始的方法。然后,Main()方法将ASP.NET配置并启动它。此时,应用程序将成为ASP.NET Core Web应用程序。
如果进一步查看 Main() 方法的正文,则会发现它通过将命令行参数 args 作为参数传递来调用 CreateHostBuilder() 方法,如下所示。
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
如下所示,CreateHostBuilder() 方法返回实现 IHostBuilder 接口的对象。主机是一个静态类,可用于创建具有预配置默认值的 IHostBuilder 实例。
CreateDefaultBuilder() 方法使用预配置的默认值创建主机构建器的新实例。在内部,它配置 Kestrel(用于ASP.NET的内部 Web 服务器)、IIS整合和其他配置。
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
在 Main()方法中,在此 IHostBuilder 对象上,调用 Build() 方法,该方法实际生成 Web 主机。
然后,它将我们asp.net Web 主机中托管我们的Asp.net Core Web 应用程序。
最后,在 Web 主机上,它称为 Run() 方法,该方法将实际运行 Web 应用程序,并开始侦听传入的 HTTP 请求。
启动类(Startup)
在设置主机时,还使用 IHostBuilder 类的 UseStartup() 扩展方法配置启动类。启动类有两种方法,如下所示。
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
ConfigureServices() 方法配置应用程序所需的服务。Startup 类的Configure() 方法设置应用程序的请求处理管道。
CreateDefaultBuilder() 方法执行的任务是什么?
作为设置 Web 主机的一部分,CreateDefaultBuilder() 方法执行几项操作。其中一些如下:
设置 Web 服务器
从各种配置源加载主机和应用程序配置
配置日志记录
在下一章, 我们将讨论CreateDefaultBuilder() 方法究竟对配置和设置 Web 服务器的作用以及应用程序的托管模型。
来源:https://www.cnblogs.com/zh7791/p/14440626.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python中的代码运行时间获取方式
MySQL 实现lastInfdexOf的功能案例
基于python使MUI登录页面的美化
![](https://img.aspxhome.com/file/2023/5/95585_0s.jpg)
python3中os.path模块下常用的用法总结【推荐】
Python中ini配置文件读写的实现
带你了解MySQL中的事件调度器EVENT
Python构建简单线性回归模型
![](https://img.aspxhome.com/file/2023/8/79738_0s.png)
Python字典循环添加一键多值的用法实例
利用LyScript实现应用层钩子扫描器
![](https://img.aspxhome.com/file/2023/6/70756_0s.png)
优化Oracle库表设计的若干方法
Python调用VBA实现保留原始样式的表格合并方法
![](https://img.aspxhome.com/file/2023/9/135159_0s.png)
python3.7.3版本和django2.2.3版本是否可以兼容
![](https://img.aspxhome.com/file/2023/4/82554_0s.png)
SQL Server技巧之快速得到表的记录总数
![](https://img.aspxhome.com/file/UploadPic/20111/20111420216938s.jpg)
纯CSS Tooltips提示
提升Python程序运行效率的6个方法
js实现微信聊天效果
win10下tensorflow和matplotlib安装教程
![](https://img.aspxhome.com/file/2023/4/118094_0s.png)
用javascript实现的仿Flash广告图片轮换效果
一个不错的js软键盘代码而且移植方便
![](https://img.aspxhome.com/file/UploadPic/up/2007081413364471.jpg)