.net core 关键概念

startup 

     startup asp.net core 的入口,在构造函数中完成环境参数的配置。

    

 其中Configure 方法是用来控制如何respond一个http请求的, 例如配置log,middleware,router等,示例:

 

 

1 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {       loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); 
2 if (env.IsDevelopment()) {
3  app.UseDeveloperExceptionPage(); 
4 app.UseDatabaseErrorPage(); 
5 app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); 
6 }
7   //asp.net 路由用法 
8 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }

 

 ConfigureServices 方法,参数是IServiceCollection,是配置依赖注入的。需要注意的是此方法是在configure之前运行的。

     在startup中的几个类:

  1. IApplicationBuilder 用来创建处理管道的。
  2. IHostingEnvironment 环境变量。
  3. ILoggerFactory  创建log日志。
  4. IServiceCollection  配置container。

   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}");

 

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:

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上的。

不过在生产环境下,不能直接部署,需要通过反向代理。

 

 

 

posted @ 2016-10-26 13:51  Ryan chen  阅读(608)  评论(0编辑  收藏  举报