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"); } app.UseStaticFiles(); app.UseIdentity(); // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715 //asp.net 用法 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
ConfigureServices 方法,參數是IServiceCollection,是配置依賴注入的。需要注意的是此方法是在configure之前運行的。
在startup中的幾個類:
middleware
和owin和nodejs一樣,netcore中的中間件也是洋蔥結構,用法也類似。如上面configure中代碼所示,添加了日志,錯誤處理,靜態文件服務器和mvc 幾個middleware。static file module 這個靜態文件中間件是沒有權限控制的。
一個簡單的中間件示例:
1 app.Run(async context =>
2 {
3 await context.Response.WriteAsync("Hello, World!");
4 });
app.run 會終止請求。
Staticfiles
當靜態文件在webroot之外時,
1 app.UseStaticFiles(new StaticFileOptions()
2 {
3 FileProvider = new PhysicalFileProvider(
4 Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
5 RequestPath = new PathString("/StaticFiles")
6 });
當使用文件目錄浏覽時,
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");
錯誤處理
1 if (env.IsDevelopment())
2 {
3 app.UseDeveloperExceptionPage();
4 }
5 else
6 {
7 app.UseExceptionHandler("/Home/Error");
8 }
配置狀態頁:
1 app.UseStatusCodePages(context =>
2 context.HttpContext.Response.SendAsync("Handler, status code: " +
3 context.HttpContext.Response.StatusCode, "text/plain"));
也可以跳轉處理,
1 app.UseStatusCodePagesWithRedirects("~/errors/{0}");
內存配置
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:
1 services.Configure<MyOptions>(Configuration);
2
3 // Configure MyOptions using code
4 services.Configure<MyOptions>(myOptions =>
5 {
6 myOptions.Option1 = "value1_from_action";
7 });
loging
1 public void Configure(IApplicationBuilder app, 2 IHostingEnvironment env, 3 ILoggerFactory loggerFactory) 4 //添加一個控制台的日志 5 loggerFactory.AddConsole.
Host
Kestrel is a cross-platform web server based on libuv,所以kestrel是跨平台的,而weblistener 是承載在windows上的。
不過在生產環境下,不能直接部署,需要通過反向代理。