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

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

     

    本人全手工打造的dotnetcore webapi 框架,可实现快速开发。地址:https://github.com/ryansecret/WebApiCore.git。 1 采用DDD模式开发,充血模型 2 添加Dapper扩展,默认实现增删改查基本操作。利用AutoMapper 做实体转换,减少重复劳动。 3 依赖注入融合Autofac,仓储层和应用层自动注入 4 实现JWT验证 5 加入swagger 文档 6 单元测试添加了xunit,MyMvc 可以方便对webapi测试 7 数据库版本控制
  • 相关阅读:
    一个bug案例分析
    《需求工程》阅读随笔-1.做什么和怎么做
    连贯接口(fluent interface)的Java实现及应用。
    代码覆盖率检测工具大全
    腾讯的一个移动端测试小工具GT
    用复制mysql/data 文件夹 下面的数据库的形式来复制数据库出现的问题
    淘客API升级后的解决方案,怎么采集淘宝的商品数据
    方维团购系统,给供货商添加省市地址
    支付宝担保交易收款接口使用
    方维分享系统首页,插入新品,用来做优化
  • 原文地址:https://www.cnblogs.com/ryansecreat/p/5993757.html
Copyright © 2020-2023  润新知