配置文件名:appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"WeChat": {
"RedirectUri": "https://libAuth.cdut.edu.cn/connect/oauth2/redirect/",
"CallBackHost": [
"192.168.244.5",
"libic.cdut.edu.cn",
"mlib.cdut.cn"
]
}
}
目标:读出WeChat:CallBackHost中的数据,判断当前数据是否包含在这个数组中。
第一步,在要使用数据的类中通过构造函数注入IConfiguration
public class WeChatController : ControllerBase
{
private readonly IConfiguration configuration;
public WeChatController(IConfiguration configuration)
{
this.configuration = configuration;
}
}
第二步,在方法中使用它
[HttpGet]
[Route("/connect/oauth2/authorize/{redirect_uri}/{scope}/{state}")]
public IActionResult OAuth(string redirect_uri, string scope, string state = "")
{
//检测合法的回调主机
var uri = new Uri(HttpUtility.UrlDecode(redirect_uri));
if (uri == null) return BadRequest();
if (configuration
.GetSection("WeChat:CallBackHost")
.GetChildren()
.Where(s => s.Value.ToUpper() == uri.Host.ToUpper())
.FirstOrDefault()
== null)
{
return BadRequest();
};
//其余逻辑计算......
}
重点内容:
configuration.GetSection("WeChat:CallBackHost")
.GetChildren()
LINQ查询
Where(s => s.Value.ToUpper() == uri.Host.ToUpper())
FirstOrDefault()