Skip to content

Commit

Permalink
支持可空类型并添加多个辅助类和扩展方法
Browse files Browse the repository at this point in the history
在 `ConfigFileHelper.cs` 中支持可空类型,改进了 `Get` 和 `Set` 方法。
在 `PekSysSetting.cs` 中添加了 `PekSysSetting` 类及其属性。
在 `HttpResponseExtensions.cs` 中添加了 JSON 和 HTML 写入方法及缓存设置方法。
在 `SessionExtensions.cs` 中添加了会话数据的 `Set` 和 `Get` 方法。
在 `DHWebHelper.cs` 中添加了多个用于处理请求和 URL 的方法。
添加了 `RequestHelper` 类,用于处理 HTTP 请求的辅助方法。
添加了 `UserAgentParser` 类,用于解析 UserAgent 字符串并判断设备类型。
  • Loading branch information
猿人易 committed Dec 17, 2024
1 parent a6f5467 commit 4d53d1f
Show file tree
Hide file tree
Showing 7 changed files with 1,069 additions and 26 deletions.
49 changes: 23 additions & 26 deletions Pek.AspNetCore/Configs/ConfigFileHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,33 @@ namespace Pek.Configs;
/// </summary>
public static class ConfigFileHelper
{
private static IConfiguration _config;
private static IConfiguration? _config;

/// <summary>
/// 得到对象属性
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Get<T>(string name = null) where T : class, new()
public static T? Get<T>(String? name = null) where T : class, new()
{
try
{
//节点名称
var sectionName = string.IsNullOrWhiteSpace(name) ? typeof(T).Name : name;
var sectionName = String.IsNullOrWhiteSpace(name) ? typeof(T).Name : name;
if (typeof(T).IsGenericType)
{
var genericArgTypes = typeof(T).GetGenericArguments();
sectionName = genericArgTypes[0].Name;
}
//判断配置文件是否有节点
if (_config.GetChildren().FirstOrDefault(i => i.Key == sectionName) == null)
if (_config?.GetChildren().FirstOrDefault(i => i.Key == sectionName) == null)
return null;

//节点对象反序列化
var spList = new ServiceCollection().AddOptions()
.Configure<T>(options => _config.GetSection(sectionName))
.BuildServiceProvider();
return spList.GetService<IOptionsMonitor<T>>().CurrentValue;
return spList.GetService<IOptionsMonitor<T>>()?.CurrentValue;
}
catch (Exception)
{
Expand All @@ -48,23 +48,20 @@ public static class ConfigFileHelper
/// </summary>
/// <param name="sectionName"></param>
/// <returns></returns>
public static String Get(String sectionName)
{
return _config.GetSection(sectionName).Value;
}
public static String? Get(String sectionName) => _config?.GetSection(sectionName).Value;

/// <summary>
/// 设置配置项
/// </summary>
/// <param name="file"></param>
/// <param name="env"></param>
public static void Set(String file = "appsettings.json", IHostEnvironment env = null)
public static void Set(String file = "appsettings.json", IHostEnvironment? env = null)
{
if (env != null)
{
_config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(file, true, true)
.AddJsonFile($"{file.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)[0]}.{env.EnvironmentName}.json", true)
.AddJsonFile($"{file.Split(['.'], StringSplitOptions.RemoveEmptyEntries)[0]}.{env.EnvironmentName}.json", true)
.Build();
}
else
Expand Down Expand Up @@ -161,7 +158,7 @@ public static void SetConfig(this ConfigurationManager config)
#endregion

#region 编辑appsettings.json
public static Object GetAppSetting(String key, String filePath = null)
public static Object? GetAppSetting(String key, String? filePath = null)
{
if (filePath == null)
{
Expand All @@ -179,30 +176,30 @@ public static Object GetAppSetting(String key, String filePath = null)

if (strArray.Length == 1)
{
return jsonObj[key];
return jsonObj?[key];
}
else if (strArray.Length == 2)
{
if (!jsonObj.ContainsKey(strArray[0]))
if (jsonObj?.ContainsKey(strArray[0]) == false)
{
return null;
}
var dic = jsonObj[strArray[0]].ToDictionary();
return dic[strArray[1]];
var dic = jsonObj?[strArray[0]]?.ToDictionary();
return dic?[strArray[1]];
}
else if (strArray.Length == 3)
{
if (!jsonObj.ContainsKey(strArray[0]))
if (jsonObj?.ContainsKey(strArray[0]) == false)
{
return null;
}
var dic = jsonObj[strArray[0]].ToDictionary();
if (!dic.ContainsKey(strArray[1]))
var dic = jsonObj?[strArray[0]]?.ToDictionary();
if (dic?.ContainsKey(strArray[1]) == false)
{
return null;
}
var dic1 = dic[strArray[1]].ToDictionary();
return dic1[strArray[2]];
var dic1 = dic?[strArray[1]]?.ToDictionary();
return dic1?[strArray[2]];
}

return null;
Expand All @@ -215,7 +212,7 @@ public static Object GetAppSetting(String key, String filePath = null)
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="filePath"></param>
public static void AddOrUpdateAppSetting<T>(String key, T value, String filePath = null)
public static void AddOrUpdateAppSetting<T>(String key, T value, String? filePath = null)
{
if (filePath == null)
{
Expand All @@ -227,7 +224,7 @@ public static void AddOrUpdateAppSetting<T>(String key, T value, String filePath
}

var json = File.ReadAllText(filePath);
var jsonObj = JsonParser.Decode(json);
var jsonObj = JsonParser.Decode(json)!;

var strArray = key.Split(":");

Expand All @@ -241,7 +238,7 @@ public static void AddOrUpdateAppSetting<T>(String key, T value, String filePath
{
jsonObj[strArray[0]] = new Dictionary<String, Object>();
}
var dic = jsonObj[strArray[0]].ToDictionary();
var dic = jsonObj[strArray[0]]!.ToDictionary();
dic[strArray[1]] = value;
jsonObj[strArray[0]] = dic;
}
Expand All @@ -251,12 +248,12 @@ public static void AddOrUpdateAppSetting<T>(String key, T value, String filePath
{
jsonObj[strArray[0]] = new Dictionary<String, Object>();
}
var dic = jsonObj[strArray[0]].ToDictionary();
var dic = jsonObj[strArray[0]]!.ToDictionary();
if (!dic.ContainsKey(strArray[1]))
{
dic[strArray[1]] = new Dictionary<String, Object>();
}
var dic1 = dic[strArray[1]].ToDictionary();
var dic1 = dic[strArray[1]]!.ToDictionary();
dic1[strArray[2]] = value;
dic[strArray[1]] = dic1;
jsonObj[strArray[0]] = dic;
Expand Down
16 changes: 16 additions & 0 deletions Pek.AspNetCore/Configs/PekSysSetting.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.ComponentModel;

using NewLife.Configuration;

namespace Pek.Configs;

/// <summary>系统通用配置</summary>
[DisplayName("系统通用配置")]
[Config("PekSys")]
public class PekSysSetting : Config<PekSysSetting>
{
/// <summary>机器人错误码。设置后拦截各种爬虫并返回相应错误,如404/500,默认0不拦截</summary>
[Description("机器人错误码。设置后拦截各种爬虫并返回相应错误,如404/500,默认0不拦截")]
[Category("通用")]
public Int32 RobotError { get; set; }
}
93 changes: 93 additions & 0 deletions Pek.AspNetCore/Extensions/HttpResponseExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using System.Text;

using NewLife.Serialization;

namespace Pek;

/// <summary>
/// Http响应(<see cref="HttpResponse"/>) 扩展
/// </summary>
public static class HttpResponseExtensions
{
#region WriteJsonAsync(写入Json)

/// <summary>
/// 写入Json
/// </summary>
/// <param name="response">Http响应</param>
/// <param name="obj">对象</param>
public static async Task WriteJsonAsync(this HttpResponse response, Object obj)
{
var json = JsonHelper.ToJson(obj);
await response.WriteJsonAsync(json).ConfigureAwait(false);
}

/// <summary>
/// 写入Json
/// </summary>
/// <param name="response">Http响应</param>
/// <param name="json">Json字符串</param>
public static async Task WriteJsonAsync(this HttpResponse response, String json)
{
response.ContentType = "application/json; charset=utf-8";
await response.WriteAsync(json).ConfigureAwait(false);
}

#endregion

#region SetCache(设置缓存头)

/// <summary>
/// 设置缓存头
/// </summary>
/// <param name="response">Http响应</param>
/// <param name="maxAge">最大有效期</param>
public static void SetCache(this HttpResponse response, Int32 maxAge)
{
if (maxAge == 0)
{
SetNoCache(response);
}
else if (maxAge > 0)
{
if (!response.Headers.ContainsKey("Cache-Control"))
{
response.Headers.Append("Cache-Control", $"max-age={maxAge}");
}
}
}

#endregion

#region SetNoCache(设置无缓存)

/// <summary>
/// 设置无缓存
/// </summary>
/// <param name="response">Http响应</param>
public static void SetNoCache(this HttpResponse response)
{
if (!response.Headers.ContainsKey("Cache-Control"))
response.Headers.Append("Cache-Control", "no-store, no-cache, max-age=0");
if (!response.Headers.ContainsKey("Pragma"))
response.Headers.Append("Pragma", "no-cache");
}

#endregion

#region WriteHtmlAsync(写入Html)

/// <summary>
/// 写入Html
/// </summary>
/// <param name="response">Http响应</param>
/// <param name="html">Html字符串</param>
public static async Task WriteHtmlAsync(this HttpResponse response, String html)
{
response.ContentType = "text/html; charset=utf-8";
await response.WriteAsync(html, Encoding.UTF8).ConfigureAwait(false);
}

#endregion

}
38 changes: 38 additions & 0 deletions Pek.AspNetCore/Extensions/SessionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using NewLife.Serialization;

namespace Pek;

/// <summary>
/// 会话(<see cref="ISession"/>) 扩展
/// </summary>
public static class SessionExtensions
{
/// <summary>
/// 设置会话
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="session">会话</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
public static void Set<T>(this ISession session, String key, T value)
{
if (String.IsNullOrWhiteSpace(key))
{
return;
}
session.Set(key, JsonHelper.ToJson(value!));
}

/// <summary>
/// 获取指定键名的值
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="session">会话</param>
/// <param name="key">键名</param>
/// <returns></returns>
public static T? Get<T>(this ISession session, String key)
{
var value = session.GetString(key);
return String.IsNullOrWhiteSpace(value) ? default : JsonHelper.ToJsonEntity<T>(value);
}
}
Loading

0 comments on commit 4d53d1f

Please sign in to comment.