当前位置:网站首页>【.Net Core】程序相关各种全局文件
【.Net Core】程序相关各种全局文件
2022-07-01 23:16:00 【又被平均了】
Program.cs
ASP.NET Core Web应用被创建后,项目中会产生两个文件:Program.cs、Startup.cs,程序中把Program.cs作为Web应用程序的入口,程序启动时会调用Startup.cs类。
这是我们配置Web Host的应用程序的入口。 program类配置应用程序基础结构,如Web Host,日志记录,依赖注入容器,IIS集成等。它们是由program类中Main方法的createdefaultbuilder方法创建,配置和构建的。
ASP.NET MVC、WebApi中 Global.asax、FilterConfig.cs 和 RouteConfig.cs等类都被Program.cs、Startup.cs取而代之。
什么是Program.cs?
Program类包含的Main方法是ASP.NET Core应用的入口点。Main方法类似于控制台应用程序 的Main方法。这是因为所有.NET Core应用程序基本上都是控制台应用程序。我们通过控制台应用程序构建其他类型的应用程序,例如MVC Web应用程序或Razor page 应用程序。
Program类的主要目的是配置应用程序基础结构。
Program类在启动时创建Web Host。然后,它配置日志记录、依赖注入容器、Kestrel Web服务器、IIS集成等。它还将框架服务添加到DI容器中,以便我们可以使用它。 Program类的代码是vs自动生成的,并且对于大多数项目来说很可能已经足够了。
什么是web host?
Web host负责启动应用程序并运行它。 在应用程序启动时创建。 Web host创建一个服务器,该服务器侦听HTTP请求。 它配置请求管道(或中间件管道)。 另外,它设置了DI容器,我们在其中添加了服务。 管理服务的生命周期也是Web host的任务。
main方法
打开program.cs。这个类只有一个Main方法
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace HelloWorld
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
这是我们应用程序的入口。
下图显示了如何创建web host
CreateWebHostBuilder 创建主机并为其提供配置。build方法使用提供的配置进行构建。Run方法运行它,然后侦听HTTP请求
ASP.NET Core中Program.cs类的Main方法
创建主机
CreateWebHostBuilder是static方法,它可以创建和配置主机,然后返回。
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
上面的语法称为“ expression bodied function member(表达式方法体)”。是C#6中引入的功能 。上面的代码与以下代码等效。
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
上面的方法使用Web Host helper静态类。WebHost helper类的CreateDefaultBuilder方法负责使用所需配置创建IWebHostBuilder实例。
CreateDefaultBuilder
- 在CreateDefaultBuilder中执行以下操作。
- 将ContentRoot设置为Directory.GetCurrentDirectory。
- 加载可选配置启用记录
- Appsettings.json
- Appsettings.{Environment}.json。
- User secrets。
- 环境变量
- 命令行参数。
- 启用记录
- 设置依赖项注入容器。
- 将Kestre l 配置为Web服务器
- 将框架服务添加到DI容器
- 将Kestrel与IIS集成
我们可以从ASP.NET Core元数据包中查看CreateDefaultBuilder的源代码。
public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
var builder = new WebHostBuilder();
if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
{
builder.UseContentRoot(Directory.GetCurrentDirectory());
}
if (args != null)
{
builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
}
builder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{
env.EnvironmentName}.json", optional: true, reloadOnChange: true);
if (env.IsDevelopment())
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
}).
UseDefaultServiceProvider((context, options) =>
{
options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
});
ConfigureWebDefaults(builder);
return builder;
}
让我们来一行一行的看看
设置ContentRoot
builder.UseContentRoot(Directory.GetCurrentDirectory());
这将ContentRoot设置为 Directory.GetCurrentDirectory。这基本上将当前目录设置为应用程序的根目录。
加载配置文件:从各种来源按以下顺序加载配置
- Appsettings.json。
- appsettings.{Environment} .json。
- User secrets。
- 环境变量。
- 命令行参数。
if (args != null)
{
builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
}
builder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{
env.EnvironmentName}.json", optional: true, reloadOnChange: true);
if (env.IsDevelopment())
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
启用记录
接下来是启用和配置日志记录的代码。
ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
}).
这将读取配置文件的“Logging”部分中指定的配置规则,并配置控制台和调试输出的日志记录。
设置DI容器
UseDefaultServiceProvider方法设置并注入依赖项容器。
UseDefaultServiceProvider((context, options) =>
{
options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
});
配置WebHost
最后,代码调用ConfigureWebDefaults方法。此方法配置Web Host。
internal static void ConfigureWebDefaults(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration((ctx, cb) =>
{
if (ctx.HostingEnvironment.IsDevelopment())
{
StaticWebAssetsLoader.UseStaticWebAssets(ctx.HostingEnvironment, ctx.Configuration);
}
});
builder.UseKestrel((builderContext, options) =>
{
options.Configure(builderContext.Configuration.GetSection("Kestrel"));
})
.ConfigureServices((hostingContext, services) =>
{
services.PostConfigure<HostFilteringOptions>(options =>
{
if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
{
var hosts = hostingContext.Configuration["AllowedHosts"]?.Split(new[] {
';' }, StringSplitOptions.RemoveEmptyEntries);
options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] {
"*" });
}
});
new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration));
services.AddTransient<IStartupFilter, HostFilteringStartupFilter>();
if (string.Equals("true", hostingContext.Configuration["ForwardedHeaders_Enabled"], StringComparison.OrdinalIgnoreCase))
{
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
services.AddTransient<IStartupFilter, ForwardedHeadersStartupFilter>();
}
services.AddRouting();
})
.UseIIS()
.UseIISIntegration();
}
Kestrel
第一种方法告诉主机使用Kestrel Web服务器。Kestrel是基于跨平台托管HTTP服务器的。该服务器允许ASP.NET Core应用程序在Windows以外的操作系统上运行。
builder.UseKestrel((builderContext, options) =>
{
options.Configure(builderContext.Configuration.GetSection("Kestrel"));
})
配置服务
配置服务并将其添加到DI 容器。
ConfigureServices((hostingContext, services) =>
{
//服务
}
使用IIS或集成
配置IIS服务器以托管应用程序。我们可以通过两种方式托管应用程序。一个在进程中托管,另一个在进程外托管。in Process在IIS Process内部运行该应用程序,并由配置UseIIS()。Out of process在单独的进程中运行,并使用Kestrel服务器。然后,IIS充当反向代理,将请求转发到Kestrel。这是通过方法配置的UseIISIntegration()。
.UseIIS()
.UseIISIntegration();
Startup class
主机已创建和配置,但是在构建和运行之前,我们需要使用应用程序进行进一步配置。我们在Startup类中执行此操作。默认情况下,该类被命名为Startup类。通过使用UseStartup方法,我们使构建者知道启动类的位置。
.UseStartup<Startup>()
启动类包含两个方法。一个是ConfigureServices(是可选的),另一个是Configure。在ConfigureServices方法中,我们配置在应用程序中创建的服务并将其添加到DI容器中。在Configure方法中,我们通过添加中间件的方式来创建请求管道。
CreateWebHostBuilder将从启动类调用ConfigureServices和configure方法,并进一步配置主机
编译并运行
CreateWebHostBuilder创建Web Host并将其返回。通过Build与Run方法调用,并且启动应用程序从而开始监听HTTP请求。
CreateWebHostBuilder(args).Build().Run();
Startup.cs
Startup.cs的作用是:在项目中用到的静态文件、管道、服务、日志、路由、数据库连接、过滤器的注册等所有有关程序运行时使用。
项目Startup.cs类:
public class Startup
{
public IConfiguration Configuration {
get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// 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)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
);
services.AddMvc();
//自动添加服务依赖
//AddTransient 每次注册服务,会创建新的仓库,以保证仓库之间独立
//仓库依赖注入系统
services.AddTransient<INoodleRepository, NoodleRepository>();
services.AddTransient<IFeedbackRepository,FeedbackRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//app.UseMvcWithDefaultRoute(); 默认路由
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(route =>
{
route.MapRoute("default","{controller=Home}/{action=Index}/{id?}");
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
从上面可以看出Startup.cs主要包含两个方法:ConfigureServices、Configure
1.ConfigureServices方法:将服务注册到容器。eg:第三方组件
services.AddMvc(); //注入MVC模块,包含MvcCore和常用的第三方库的服务和方法
services.AddTransient<INoodleRepository, NoodleRepository>(); //自动添加服务依赖。瞬时注入,每次都会创建一个新的对象,以保证对象之间的独立性
services.AddSingleton<IStudentRepository,MockStudentRepository>(); //单例注入,创建的对象在所有的地方所有的请求会话创建的都是相同的
services.AddScoped<IStudentRepository,MockStudentRepository>(); //作用域注入,创建的对象在同一个请求会话时是相同的
2.Configure方法:配置Http请求管道。 eg:session、cookie
HostingEnvironment.IsDevelopment(); //判断当前运行环境是否是 Microsoft,如果是则返回true。
//如果要判断其他运行环境,比如 Linux,则使用 env.IsEnvironment(“environmentname”) environmentname为要验证的环境名称。
app.UseStaticFiles(); //使用静态文件
//使用MVC管道路径,可以在这个配置路由等操作
app.UseMvc(route =>
{
route.MapRoute(“default”,“{controller=Home}/{action=Index}/{id?}”);
});
实战
1. .net core使用session:
ConfigureServices方法: services.AddSession(); //注入session
Configure方法:app.UseSession();
Controller:
//[Route("[controller]/[action]")]
public class HomeController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
HttpContext.Session.SetString("code","123456");
return View();
}
public String About()
{
ViewBag.Code = HttpContext.Session.GetSession("code");
return View();
}
}
2. .net core使用Cache:
ConfigureServices方法: services.AddMemoryCache(); //注册缓存服务
Controller:
public class HomeController : Controller
{
private IMemoryCache _cache;
public HomeController (IMemoryCache memoryCache )
{
_cache = memoryCache ;
}
}
设置缓存: _cache.set(“key”,“value”);
移除缓存: _cache.remove(“key”);
appsettings.json:Development(开发)Staging(预演)Production(生产)
ASP.NET Core基于以下环境变量读取配置文件 appsettings.json:Development(开发)Staging(预演)Production(生产)它们的文件名都是诸如这样的名称 appsettings.Development.json。
在运行的时候我们怎么知道是从哪个文件取值呢?
首先这个值来自键值对的配置,总结一下设置变量的方式,一共有两个:
- 通过使用关键字来设置 DOTNET_ENVIRONMENT。
- 通过键值ASPNETCORE_ENVIRONMENT来设置。
- 其中ASPNETCORE_ENVIRONMENT优先级高于 DOTNET_ENVIRONMENT。
再总结一下设置运行时环境的方法。
(1)如果你是代码开发者,使用Visual Studio开发者,在工具里运行和调试软件,右键选择项目属性,如图:
其实配置文件保存在:Properties \ launchSettings.json
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"nativeDebugging": true
}
(2)如果你使用的Visual Studio Code,那么你可直接编辑或新建文件.vscode / launch.json
例如:
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
// Configuration ommitted for brevity.
"env": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "https://localhost:5001",
"ASPNETCORE_DETAILEDERRORS": "1",
"ASPNETCORE_SHUTDOWNTIMEOUTSECONDS": "3"
}
(3)如果你只是运行代码那么在服务器上需要设置环境变量,一种是临时设置,一种是全局设置,各命令行需要根据操作系统变化而不同,(自行百度Linux各系统设置环境变量的方法)例如Windows下:
set ASPNETCORE_ENVIRONMENT=Staging
dotnet run --no-launch-profile
(4)如果你什么都不做,那默认加载的是Production,也就是appsettings.Production.json(不建议这么做)。
(5)如果你是托管在IIS宿主下,那么是还会有一个Web.config的供IIS加载,可在Web.config中添加环境变量例如:
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
<environmentVariable name="COMPLUS_ForceENC" value="1" />
</environmentVariables>
(6)如果你是在Linux下部署依靠supervisor托管程序,那么在supervisor配置文件中就有相关环境变量的配置:
[program:Own.WebSite]
command=/bin/bash -c "dotnet Own.WebSite.dll"
directory=/home/wwwroot/Own.WebSite/
stderr_logfile=/tmp/Own.WebSite.error.log
stdout_logfile=/tmp/Own.WebSite.stdout.log
environment=ASPNETCORE_ENVIRONMENT=Production
user=root
stopsignal=INT
autostart=true
autorestart=true
startsecs=3
launchsettings.json
- 您将在项目根文件夹的**“Properties”**文件夹中找到此文件。
- 当我们从 Visual Studio 或使用.NET Core CLI 运行此 ASP.NET Core 项目时,将使用此文件中的设置。
- 此文件仅用于本地开发环境。我们不需要把它发布到生产环境的 Asp.net Core 程序中。
- 如果您希望您的 Asp.Net Core 应用程序在发布和部署应用程序时使用某些独立的设置,请将它们存储在
appsettings.json 文件中。我们通常将应用程序的配置信息存储在此文件中,比如数据库连接字符串。 - 我们还可以使用不同环境的 appsettings.json 文件。例如,appsettings.Staging.json
用于临时环境。在- ASP.NET Core 中,除了 appsettings.json
文件外,我们还可以配置源,如环境变量,用户密钥,命令行参数甚至创建属于我们自己的自定义配置源。
launchSettings.json 文件:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:3290",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"StudentManagement": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
请注意,我们有两个配置信息:
IIS Express 和 StudentManagement
当我们通过按CTRL + F5或只是F5从 Visual Studio 运行项目时。 默认情况下,使用调用配置文件名称"commandName": “IISExpress”,。 另外一种情况,如果我们使用.NET Core CLI(dotnet run)运行项目,则使用带有"commandName": “Project”,的配置文件 。
我们可以通过单击 Visual Studio 中的下拉列表来更改要使用的配置文件中 .commandName 属性,修改默认设置。
默认值可以是:
- 项目
- IISExpress
- IIS
此值与项目文件中的AspNetCoreHostingModel元素的值会有对应关系,会一起指定要启动的内部和外部 Web 服务器(反向代理服务器)。
commandName | AspNetCoreHostingModel 的值 | Internal Web Server(内部服务器) | External Web Server(外部服务器) |
---|---|---|---|
项目 | 忽略托管设置的值 | 只使用一个 Web 服务器 - Kestrel | 只使用一个 Web 服务器 - Kestrel |
IISExpress | 进程内托管(InProcess) | 只使用一个 Web 服务器 - IIS Express | 只使用一个 Web 服务器 - IIS Express |
IISExpress | 进程外托管(OutOfProcess) | Kestrel | IIS Express |
IIS | 进程内托管(InProcess) | 只使用一个 Web 服务器 - IIS | 只使用一个 Web 服务器 - IIS |
IIS | 进程外托管(OutOfProcess) | Kestrel | IIS |
您还可以通过直接编辑 launchSettings.json 文件中的设置,也可以使用 Visual Studio 提供的图形用户界面(GUI)更改设置。
通过 GUI 来设置
在 Visual Studio 的解决方案资源管理器中右键单击项目名称,然后从上下文菜单中选择“属性”。 单击项目“属性”窗口中的“调试”选项卡,如下图:
使用 GUI 我们可以更改launchSettings.json文件中的设置。
注意,环境变量“ASPNETCORE_ENVIRONMENT”设置的默认设置为“Development”。
我们可以将此值更改为Staging或Production,具体取决于我们是在Staging还是Production环境中运行此项目。
我们还可以添加新的环境变量。这些环境变量在我们的 Asp.Net Core 应用程序中都可用,我们可以包含根据这些环境变量的值有条件地执行的代码。
例如,请参考Startup.cs文件中的Configure()方法中的以下代码
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//其他的代码
}
仅当环境为“ Development”时,才会显示“ 开发异常页面”。
来源
ASP.NET Core中Startup.cs介绍
ASP.NET Core Program.cs
ASP.NET Core 中appsettings各环境设置以及使用
ASP.NET Core 中 launchsettings.json 启动配置文件
边栏推荐
- 共享电商的背后: 共创、共生、共享、共富,共赢的共富精神
- 有没有一段代码,让你为人类的智慧所折服
- Typescript enumeration
- SWT / anr problem - SWT causes low memory killer (LMK)
- Is it safe to choose mobile phone for stock trading account opening in Shanghai?
- Daily three questions 6.28
- 内存泄露和内存溢出的区别是什么?
- What is the relationship between modeling and later film and television?
- 2021 RoboCom 世界机器人开发者大赛-高职组复赛
- 转行软件测试,知道这四点就够了!
猜你喜欢
深度学习 | 三个概念:Epoch, Batch, Iteration
CKS CKA ckad change terminal to remote desktop
Why is PHP called hypertext preprocessor
"35 years old, the boss of the company, with a monthly salary of 20000, give away takeout": the times abandoned you, not even saying goodbye
How to display real-time 2D map after rviz is opened
RPA: Bank digitalization, business process automation "a small step", and loan review efficiency "a big step"
Redis data types and application scenarios
【小程序】通过scroll-view组件实现左右【滑动】列表
认识--Matplotlib
[applet] realize the left and right [sliding] list through the scroll view component
随机推荐
图的遍历之深度优先搜索和广度优先搜索
有没有一段代码,让你为人类的智慧所折服
Aaai22 | structural tagging and interaction modeling: a "slim" network for graph classification
会声会影2022智能、快速、简单的视频剪辑软件
2021 RoboCom 世界机器人开发者大赛-本科组初赛
Redis 主从同步
Microservice stability management
CKS CKA ckad change terminal to remote desktop
CADD course learning (3) -- target drug interaction
[micro service sentinel] sentinel integrates openfeign
Zhao Fuquan: to ensure supply in the short term, we should build a safe, efficient and resilient supply chain in the long term
"35 years old, the boss of the company, with a monthly salary of 20000, give away takeout": the times abandoned you, not even saying goodbye
2022 safety officer-c certificate examination question simulation examination question bank and simulation examination
Redis AOF日志
What is the difference between memory leak and memory overflow?
13 MySQL-约束
为什么PHP叫超文本预处理器
SWT/ANR问题--SWT 导致 low memory killer(LMK)
Commemorate becoming the first dayus200 tripartite demo contributor
Notes to problems - file /usr/share/mysql/charsets/readme from install of mysql-server-5.1.73-1 glibc23.x86_ 64 c