.Net 笔记

1.本地调试证书过期问题

//.Net 在调试https 报证书不可信,导致经过网关一直报502
//原因是自带的证书过期了,用cmd命令先删除之前的证书,再安装,解决。
dotnet dev-certs https --clean   
dotnet dev-certs https --trust

2.配置文件读写

//引入配置文件
var _config = new ConfigurationBuilder()
                 .AddInMemoryCollection() //将配置文件的数据加载到内存中
                 .SetBasePath(basePath)//指定配置文件所在的目录
                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                 //指定加载的配置文件  --**记得始终复制**
                 .Build();//编译  

//Program中从appsettings.json文件读取配置到实体类		 
//在其它类库项目中需要引入 Microsoft.Extensions.Configuration.Binder 拓展
## 注入:
//方法一
builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection("JwtConfig"));
//方法二
JwtConfig jwtConfig = new JwtConfig();
builder.Configuration.Bind("JwtConfig",jwtConfig);
//方法三
builder.Configuration.GetSection("JwtConfig").Get<JwtConfig>();

## 获取
//在类的构造函数中获取:IOptionsMonitor<JwtConfig> jwtConfig
private JwtConfig _jwtConfig;
public JwtAuthTokenService(IOptionsMonitor<JwtConfig> jwtConfig)
{
    _jwtConfig = jwtConfig.CurrentValue;
}

//配置相关的Negut包:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Configuration.Binder
Microsoft.Extensions.Options

IOptions<> //是单例,因此一旦生成了,除非通过代码的方式更改,它的值是不会更新的。
IOptionsMonitor<> //也是单例,但是它通过IOptionsChangeTokenSource<> 能够和配置文件一起更新,也能通过代码的方式更改值。
IOptionsSnapshot<> //作用域模式,同一次请求获取到的值不会变

ConfigurationBuilder configBuilder = new ConfigurationBuilder();
configBuilder.AddJsonFile("appsettings.json",optional:true,reloadOnChange:true);

IConfigurationRoot configRoot = configBuilder.Build(); 
builder.Services.AddOptions().Configure<Config>(x=>configRoot.Bind(x))//绑定整个配置
.Configure<RedisConfig>(x=>configRoot.GetSection("RedisConfig").Bind(x));//绑定配置节点


3. IOC/DI相关

//在Program中测试获取scope作用域模式的服务,不可用app.Service.ServiceProvider 会报错,解决方法:
using (var serviceScope = app.Services.CreateScope())
{
    var client = serviceScope.ServiceProvider.GetRequiredService<IApplicationMetaService>();
    var a = await client.GetAppMetas(8, "0hwjk9uloncij", "table");
}

4. 将控制台程序变成后台托管任务

var builder = new HostBuilder();
builder.ConfigureServices((context, services) =>
{
    services.AddHostedService<BackTask>();
});

var host = builder.Build();
host.Start();

4.取最后一个过滤器。类和方法上都有该过滤器,会都触发,这时候需要处理只触发方法上的过滤器

var endpoint = context.HttpContext.Features.Get<IEndpointFeature>()?.Endpoint;
if (endpoint == null)
{
    await next();
    return;
}
var filter = endpoint?.Metadata.LastOrDefault(x => x is OrgPermissionFilter) as OrgPermissionFilter;

5.HttpContext请求上下文

//1.获取request ip
HttpContext.Connection.RemoteIpAddress.ToString();

//2.获取请求参数
Dictionary<string, string?> querys = Request.Query.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault());
Dictionary<string, string?> headers = Request.Headers.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault());
try
{
    string bodyJson = string.Empty;
    var stream = HttpContext.Request.Body;
    long? length = HttpContext.Request.ContentLength;
    if (length != null && length > 0)
    {
        using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
        bodyJson = await streamReader.ReadToEndAsync();
    }
    JToken body = JToken.Parse(bodyJson);
}
catch (Exception)
{
}
posted @ 2023-07-26 11:38  Net开发-孔明  阅读(44)  评论(0编辑  收藏  举报