第五章 CORE
5.1 CORE 介绍
5.1.1 CORE 应用
Program.cs
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
5.1.2 Startup:用来定义请求处理管道和配置应用需要的服务,该类必须是公开(public)的,而且必须含有以下两个方法。
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
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, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
5.1.3 服务
5.1.4 中间件
5.1.5 服务器
5.1.6 内容根目录
默认情况下,内容根目录与宿主目录应用的可执行程序的应用根目录相同;其他位置可以通过WebHostBuilder来设置。
5.1.7 网站根目录
。
5.1.8 配置
5.1.9 环境
5.2 Application StartUp
5.2.1 实战中间件
-
Core Web Application项目,选择空模板
然后为项目添加一个Microsoft.Extensions.Loggin.Console
NuGet命令执行:
Install-Package Microsoft.Extensions.Logging.Console
- 新建一个类RequestIpMiddleware.cs
public class RequestIpMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public RequestIpMiddleware(RequestDelegate next, ILoggerFactory loggetFactory)
{
_next = next;
_logger = loggetFactory.CreateLogger<RequestIpMiddleware>();
}
public async Task Invoke(HttpContext context)
{
_logger.LogInformation("User Ip :" +
context.Connection.RemoteIpAddress.ToString());
await _next.Invoke(context);
}
}
- 再建一个RequestIPExtensions.cs
public static class RequestIPExtensions
{
public static IApplicationBuilder UseRequestIp(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestIpMiddleware>();
}
}
这样就编写好了一个中间件(好吧,不知所以……)
-
使用中间件,在Startup.cs中添加app.UseRequestIp();