startup
startup asp.net core 的入口,在构造函数中完成环境参数的配置。
其中Configure 方法是用来控制如何respond一个http请求的, 例如配置log,middleware,router等,示例:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug();
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error");
}
//asp.net 路由用法
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
ConfigureServices
方法,参数是IServiceCollection,是配置依赖注入的。需要注意的是此方法是在configure之前运行的。
在startup中的几个类:
- IApplicationBuilder 用来创建处理管道的。
- IHostingEnvironment 环境变量。
- ILoggerFactory 创建log日志。
- IServiceCollection 配置container。
middleware
和owin和nodejs一样,netcore中的中间件也是洋葱结构,用法也类似。如上面configure中代码所示,添加了日志,错误处理,静态文件服务器和mvc 几个middleware。static file module 这个静态文件中间件是没有权限控制的。
一个简单的中间件示例:
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
});
app.run 会终止请求。
Staticfiles
当静态文件在webroot之外时,
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles")
});
当使用文件目录浏览时,
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages")
});
并且需要在service中添加
public void ConfigureServices(IServiceCollection services)
{
services.AddDirectoryBrowser();
}
Mime
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
// Remove MP4 videos.
provider.Mappings.Remove(".mp4"); 错误处理
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
配置状态页:
app.UseStatusCodePages(context =>
context.HttpContext.Response.SendAsync("Handler, status code: " +
context.HttpContext.Response.StatusCode, "text/plain"));
也可以跳转处理,
app.UseStatusCodePagesWithRedirects("~/errors/{0}");
Configuration
内存配置
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection();
var config = builder.Build();
config["somekey"] = "somevalue";
也可以通过json文件配置:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-26e8893e-d7c0-4fc6-8aab-29b59971d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
Configuration = builder.Build();
配置option:
services.Configure<MyOptions>(Configuration); // Configure MyOptions using code
services.Configure<MyOptions>(myOptions =>
{
myOptions.Option1 = "value1_from_action";
});
loging
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
//添加一个控制台的日志
loggerFactory.AddConsole.
Host
Kestrel is a cross-platform web server based on libuv,所以kestrel是跨平台的,而weblistener 是承载在windows上的。
不过在生产环境下,不能直接部署,需要通过反向代理。