.net core 关键概念

本文围绕ASP.NET Core展开,介绍了startup作为入口,在构造函数完成环境参数配置,配置依赖注入方法在configure前运行。还提及中间件为洋葱结构,给出简单示例。此外,阐述了静态文件处理、配置方式、日志、主机等内容,指出生产环境需反向代理。

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

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

 

 

 

转载于:https://www.cnblogs.com/ryansecreat/p/5993757.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值