2022年07月06日

ASP .Net Core

.NET CLI

.NET 命令行接口 (CLI) 工具是用于开发、生成、运行和发布 .NET 应用程序的跨平台工具链。

官网:https://docs.microsoft.com/zh-cn/dotnet/core/tools/

命令行创建项目

查看dotnet命令帮助

> dotnet --help

查看项目模板列表

> dotnet new -l

创建控制台模板项目

> dotnet new console

运行

> dotnet run

单元测试

创建Nunit测试项目

image-20220706141233078


https://www.bilibili.com/video/BV1m3411T7oi

鉴权授权(p40)

Cookie+Session授权

p41 鉴权实现 授权未实现

异步编程

异步方法用async关键字修饰,返回值一般是Task<T>,T是返回类型。

使用方法在方法前加上await关键字。

public async Task Test01()
{//往记事本中写入Hello
    //D:\test
    string fileName = @"D:\test\test.txt";
    await File.WriteAllTextAsync(fileName, "Hello");
}

LINQ

Func

封装一个具有参数并有返回类型值的方法。

Action

封装具有单参数且不返回值的方法。

Func<int, int, int> sum = (x, y) => x + y;
Console.WriteLine(sum(2, 3)); //5

Func<int, int> sum1 = x => x + 1 ;
Console.WriteLine(sum1(2)); //3

Action<int> sum2 = i => Console.WriteLine(i + "ok");
sum2(99); //99ok

Linq

using System.Collections.Generic;
using System.Linq;
//Where
int[] nums = new int[] { 1, 2, 3, 4, 5};
IEnumerable<int> result = nums.Where(a => a > 2);
foreach (var item in result)
{
    Console.WriteLine(item); //3 4 5
}
//Count
Console.WriteLine(nums.Count(a => a < 3)); //2
//Any:是否至少有一条数据
Console.WriteLine(nums.Any(a => a > 100)); //False
//Single:有且只有一条满足要求的数据
Console.WriteLine(nums.Single(a => a == 2)); //2
//SingleOrDefault:最多只有一条满足要求的数据
Console.WriteLine(nums.SingleOrDefault(a => a == 11)); //0
https://www.bilibili.com/video/BV1pK41137He?p=25 时间=>11:54
//First:至少有一条,返回第一条
//FirstOrDefault:返回第一条或默认值

依赖注入

不使用依赖注入

static void Main(string[] args)
{
    ICar car = new MyCar();
    car.Name = "布加迪威龙";
    car.PrintName();          //车的名字是:布加迪威龙

    Console.WriteLine("Hello World!");
    Console.ReadKey();
}

public interface ICar
{
    string Name { get; set; } //车的名字
    void PrintName();         //打印车的名字
}

public class MyCar : ICar
{
    public string Name { get; set; }

    public void PrintName()
    {
        Console.WriteLine($"车的名字是:{Name}");
    }
}

使用依赖注入

using Microsoft.Extensions.DependencyInjection; //NuGet安装

static void Main(string[] args)
{
    ServiceCollection service = new ServiceCollection();
    service.AddTransient<MyCar>(); //AddTransient瞬态,AddScoped范围,AddSingleton单例
    using (ServiceProvider sp = service.BuildServiceProvider()) //ServiceProvider服务定位器
    {
        MyCar myCar = sp.GetService<MyCar>();
        myCar.Name = "玛莎拉蒂";
        myCar.PrintName(); //车的名字是:玛莎拉蒂
    }

    Console.WriteLine("Hello World!");
    Console.ReadKey();
}

public interface ICar
{
    string Name { get; set; } //车的名字
    void PrintName();         //打印车的名字
}

public class MyCar : ICar
{
    public string Name { get; set; }

    public void PrintName()
    {
        Console.WriteLine($"车的名字是:{Name}");
    }
}

配置文件

根据key获取

配置文件myconfig.json

{
  "name": "zs",
  "age": "24",
  "score": {
    "math": 90.5
  }
}

image-20220706175629098

image-20220706175730555

重新生成项目,运行

using Microsoft.Extensions.Configuration; //NeGet安装
using Microsoft.Extensions.Configuration.Json;

static void Main(string[] args)
{
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
    IConfigurationRoot configurationRoot = configurationBuilder.Build();
    string name = configurationRoot["name"];
    string age = configurationRoot["age"];
    string math = configurationRoot.GetSection("score:math").Value;
    Console.WriteLine(name); //zs
    Console.WriteLine(age); //24
    Console.WriteLine(math); //90.5

    Console.WriteLine("Hello World!");
    Console.ReadKey();
}

映射为类获取

{
  "name": "zs",
  "age": "24",
  "score": {
    "math": 90.5,
    "english":  99
  }
}
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Binder; //NeGet安装

static void Main(string[] args)
{
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
    IConfigurationRoot configurationRoot = configurationBuilder.Build();
    Score score = configurationRoot.GetSection("score").Get<Score>();
    //英语成绩:99,数学成绩:90.5.
    Console.WriteLine($"英语成绩:{score.English},数学成绩:{score.Math}."); 

    Console.WriteLine("Hello World!");
    Console.ReadKey();
}

public class Score
{
    public double Math { get; set; }
    public double English { get; set; }
}

依赖注入获取

IOptionsMonitor:配置文件一改变就读取新的值

IOptionsSnapshot:在一个范围(一次http请求)内读取一次配置文件

NeGet安装:

using Microsoft.Extensions.Options;
using Microsoft.Extensions.Configuration.Binder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

https://www.bilibili.com/video/BV1pK41137He?p=40 时间:20

config.json

{
  "name": "zs",
  "age": "24",
  "score": {
    "math": 90.5,
    "english":  99
  }
}

Score.cs

public class Score
{
    public double Math { get; set; }
    public double English { get; set; }
}

Test01.cs

using Microsoft.Extensions.Options; //NetGet安装

class Test01
{
    private readonly IOptionsSnapshot<Score> options;

    public Test01(IOptionsSnapshot<Score> options)
    {
        this.options = options;
    }

    public void Print()
    {
        Score options = this.options.Value;
        Console.WriteLine($"数学成绩:{options.Math},英语成绩:{options.English}");
    }
}

Main

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection; //NeGet安装

static void Main(string[] args)
{
    ServiceCollection services = new ServiceCollection();
    services.AddScoped<Test01>();

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
    IConfigurationRoot configurationRoot = configurationBuilder.Build();

    //configurationRoot.Bind(e)把Score绑定到根节点上; json:{"math":90.5,"english":99}
    services.AddOptions()
        .Configure<Score>(e => configurationRoot.GetSection("score").Bind(e)); 

    using (var serviceProvider = services.BuildServiceProvider())
    {
        var test01 = serviceProvider.GetRequiredService<Test01>();
        test01.Print(); //数学成绩:90.5,英语成绩:99
    }

    Console.WriteLine("Hello World!");
    Console.ReadKey();
}