.Net Core开发学习(一) ——Startup 类
启动配置
Startup类位于:项目名称 > Startup.cs
程序启动默认配置为Startup类
位于:项目名称 > Program.cs
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>();
});
}
Startup类结构
public class Startup
{
/// <summary>
/// Startup 初始化
/// </summary>
/// <param name="configuration">程序配置接口</param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
/// 程序配置
/// </summary>
public IConfiguration Configuration { get; }
/// <summary>
/// 配置服务
/// </summary>
/// <param name="services">服务配置接口</param>
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
/// <summary>
/// 应用配置
/// </summary>
/// <param name="app">应用配置接口</param>
/// <param name="env">应用环境</param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//Development开发|Other环境判断
if (env.IsDevelopment())
{
//使用开发人员错误页
app.UseDeveloperExceptionPage();
}
else
{
//使用自定义错误页
app.UseExceptionHandler("/Home/Error");
//使用HTTP严格安全传输
app.UseHsts();
}
//使用Https
app.UseHttpsRedirection();
//使用静态文件
app.UseStaticFiles();
//使用路由
app.UseRouting();
//启用身份验证
app.UseAuthorization();
//配置路由
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
IConfiguration 程序配置接口——读取文件和内存中的配置
配置文件:项目名称 > appsettings.Development.json
{
"HelloWorld": {
"Message": "HelloWorld",
"Type" : 0
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
创建类:HelloWorld.cs
public class HelloWorld
{
public const string Position = "HelloWorld";
public string Message { get; set; }
public int Type { get; set; }
}
编辑 Startup.cs > Startup()构造方法
/// <summary>
/// Startup 初始化
/// </summary>
/// <param name="configuration">程序配置接口</param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
//获取配置对象
HelloWorld hw = configuration.GetSection(HelloWorld.Position).Get<HelloWorld>();
Console.WriteLine("Message:{0} Type:{1}", hw.Message, hw.Type);
}
其他方式
//方式 1
HelloWorld hw = configuration.GetSection(HelloWorld.Position).Get<HelloWorld>();
//方式 2
HelloWorld hw1 = new HelloWorld();
configuration.GetSection(HelloWorld.Position).Bind(hw1);
控制台输出
Message:HelloWorld Type:0
IServiceCollection服务配置接口——配置常用服务及依赖注入
这里仅讲解依赖注入,常用服务可自行查看
创建依赖类 MyDependency.cs
public class MyDependency : IMyDependency
{
public Task WriteMessage(string message)
{
Console.WriteLine(
$"MyDependency.WriteMessage called. Message: {message}");
return Task.FromResult(0);
}
}
创建依赖类接口 IMyDependency.cs
public interface IMyDependency
{
Task WriteMessage(string message);
}
编辑 Startup.cs > ConfigureServices()方法
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//为 IMyDependency 注册 MyDependency
services.AddScoped<IMyDependency, MyDependency>();
}
编辑 任意Controller控制器
private readonly IMyDependency _myDependency;
public HomeController(MyDependency myDependency)
{
_myDependency = myDependency;
_myDependency.WriteMessage("HelloWorld");
}
在请求Controller时输出
MyDependency.WriteMessage called. Message: HelloWorld
服务生命周期
//请求时创建
services.AddTransient<T, T>();
//连接创建
services.AddScoped<T, T>();
//第一次请求创建
services.AddSingleton<T, T>();
IApplicationBuilder应用配置接口——配置中间件
编辑 Startup.cs > Configure()方法
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use(async (context, next) =>
{
Console.WriteLine("Use before");
await next.Invoke();
Console.WriteLine("Use after");
});
app.Run(async (context) =>
{
Console.WriteLine("Run before");
await context.Response.WriteAsync("HelloWorld");
Console.WriteLine("Run after");
});
}
控制台输出
Use before
Run before
Run after
Use after
浏览器输出
HelloWorld
如上可见:
Use最先执行,调用
next.Invoke();
时执行Run,最后在回到Use执行完毕。
1、Use的作用是做请求前后的处理。
2、Run会拦截所有请求,所以在浏览器上会显示HelloWorld。
常用方法(持续更新)
IApplicationBuilder.UseEndpoints() 配置路由
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
//默认配置为controller/action/id?
//可根据需求自行更改
pattern: "{controller=Home}/{action=Index}/{id?}");
});
IApplicationBuilder.UseExceptionHandler()配置异常捕获
//异常捕获
app.UseExceptionHandler(app => {
app.Run(async context => await ErrorEvent(context, "/Home/Error"));
});
//异常事件
public Task ErrorEvent(HttpContext context, string error_page) {
//获取异常
var feature = context.Features.Get<IExceptionHandlerFeature>();
var error = feature?.Error;
Console.WriteLine("Error:" + error.Message);
//重定向到指定页面
context.Response.Redirect(error_page);
return context.Response.CompleteAsync();
}
IWebHostEnvironment主机环境——不同环境不同处理
在自动生成的Startup.cs > Configure()方法中,有如下代码
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//判断不同执行环境,做不同处理
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
}
env.IsDevelopment()判断是否为开发环境
提供的方法如下:
IsDevelopment() //判断开发环境
IsProduction() //判断生产环境
IsStaging() //判断演示环境
IsEnvironment(string environmentName) //根据名称判断任意环境
修改配置环境
文件:项目名 > Properties > launchSettings.json
找到
"profiles"
下有两个运行环境,一个为IIS Express,另一个为你的项目名(Kestrel服务器),找到其中名为
environmentVariables
的列,修改ASPNETCORE_ENVIRONMENT的值即可修改当前运行环境