网站首页 网站源码
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.Enumeration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using AngleSharp.Dom;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
namespace Dpz.Core.Infrastructure;
public static class DpzAppBuilderExtensions
{
public static IApplicationBuilder Init(this IApplicationBuilder app)
{
BsonSerializer.RegisterSerializer(typeof(Date), new DateBsonSerializer());
app.GetHostingEnvironment();
var appBuilder = app.HandlerOtherStatusCode();
return appBuilder;
}
/// <summary>
/// 处理非200状态码
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder HandlerOtherStatusCode(this IApplicationBuilder app)
{
var appBuilder = app.UseStatusCodePages(async x =>
{
if (x.HttpContext.Response.StatusCode == 404)
{
var envService = app.ApplicationServices.GetService<IWebHostEnvironment>();
x.HttpContext.Response.ContentType = "text/html";
await x.HttpContext.Response.SendFileAsync(
Path.Combine(envService?.WebRootPath ?? "", "NotFound.html")
);
}
else
{
x.HttpContext.Response.ContentType = "text/plain";
await x.HttpContext.Response.WriteAsync(
"Status code page, status code: " + x.HttpContext.Response.StatusCode
);
}
});
//app.UseExceptionHandler(new ExceptionHandlerOptions
//{
// ExceptionHandler = async x =>
// {
// await x.Response.WriteAsync("1");
// }
//});
return appBuilder;
}
//public static IServiceCollection AddPasswordAndCookiesGuides(this IServiceCollection services)
//{
// services.Configure<IdentityOptions>(options =>
// {
// // 密码规则
// options.Password.RequireDigit = true;
// options.Password.RequireLowercase = true;
// options.Password.RequireNonAlphanumeric = true;
// options.Password.RequireUppercase = true;
// options.Password.RequiredLength = 6;
// options.Password.RequiredUniqueChars = 1;
// // 锁定设置
// options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
// options.Lockout.MaxFailedAccessAttempts = 5;
// options.Lockout.AllowedForNewUsers = true;
// // 允许出现的字符
// options.User.AllowedUserNameCharacters =
// "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
// options.User.RequireUniqueEmail = false;
// });
// services.ConfigureApplicationCookie(options =>
// {
// // Cookie 设置
// options.Cookie.HttpOnly = true;
// options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
// options.LoginPath = "/Identity/Account/Login";
// options.AccessDeniedPath = "/Identity/Account/AccessDenied";
// options.SlidingExpiration = true;
// });
//}
/// <summary>
/// 获取有关运行应用程序的Web托管环境的信息。
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static void GetHostingEnvironment(this IApplicationBuilder app)
{
if (
app.ApplicationServices.GetService(typeof(IWebHostEnvironment))
is IWebHostEnvironment env
)
{
EnvironmentInfo.ContentRootPath = env.ContentRootPath;
EnvironmentInfo.EnvironmentName = env.EnvironmentName;
EnvironmentInfo.WebRootPath = env.WebRootPath;
}
}
/// <summary>
/// 生成MD5
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GenerateMd5(this string str)
{
var bytes = MD5.HashData(Encoding.Default.GetBytes(str));
return BitConverter.ToString(bytes).Replace("-", "");
}
/// <summary>
/// 生成MD5 小写
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GenerateHashMd5(this string str)
{
var result = string.Join(
"",
from x in MD5.HashData(Encoding.Default.GetBytes(str))
select x.ToString("x2")
);
return result;
}
/// <summary>
/// 将当前时间转换为时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static long ToTimeStamp(this DateTime dateTime)
{
var timeSpan =
dateTime.ToUniversalTime() - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
var timeStamp = (long)timeSpan.TotalSeconds;
return timeStamp;
}
/// <summary>
/// 遍历集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action"></param>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action(item);
}
}
/// <summary>
/// 获取集合的下标
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="item"></param>
/// <returns></returns>
public static int IndexOf<T>(this IEnumerable<T> source, T item)
{
var array = source.ToArray();
return Array.IndexOf(array, item);
}
/// <summary>
/// 将时间戳转换为DateTime
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime ToDateTime(this long timeStamp)
{
var utcTime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddSeconds(timeStamp);
return utcTime.LocalDateTime;
}
/// <summary>
/// 从Html中获取所有图片
/// </summary>
/// <param name="images"></param>
/// <returns></returns>
public static List<string> ToImages(this IHtmlCollection<IElement> images)
{
return images
.Select(x => x.Attributes["src"])
.Where(x => x != null)
.Select(x => x!.Value.Split('/'))
.Where(x => x.Length > 0)
.Select(x =>
{
ObjectId.TryParse(x.Last(), out var id);
return id;
})
.Where(x => x != ObjectId.Empty)
.Select(x => x.ToString())
.ToList();
}
/// <summary>
/// 从Html中获取所有图片
/// </summary>
/// <param name="images"></param>
/// <returns></returns>
public static List<ObjectId> ToObjectIdImages(this IHtmlCollection<IElement> images)
{
return images
.Select(x => x.Attributes["src"])
.Where(x => x != null)
.Select(x => x!.Value.Split('/'))
.Where(x => x.Length > 0)
.Select(x =>
{
ObjectId.TryParse(x.Last(), out var id);
return id;
})
.Where(x => x != ObjectId.Empty)
.ToList();
}
/// <summary>
/// 只替换第一次匹配的指定的字符串,
/// </summary>
/// <param name="str"></param>
/// <param name="oldStr">需要替换的字符串</param>
/// <param name="newStr">新字符</param>
/// <returns></returns>
public static string ReplaceOne(this string str, string oldStr, string newStr)
{
var index = str.IndexOf(oldStr, StringComparison.Ordinal);
if (index >= 0)
return string.Concat(str.AsSpan(0, index), newStr, str.AsSpan(index + oldStr.Length));
return str;
}
public static bool WildCardMatch(this string wildCard, string value)
{
return wildCard.Equals(value, StringComparison.OrdinalIgnoreCase)
|| FileSystemName.MatchesSimpleExpression(wildCard, value);
// var reg = "^" + Regex.Escape(wildCard).Replace("\\?", ".").Replace("\\*", ".*") + "$";
// return Regex.IsMatch(value, reg);
}
public static string ToQueryString(this NameValueCollection? collection)
{
if (collection == null || collection.Count == 0)
{
return "";
}
var sb = new StringBuilder();
var keys = collection.AllKeys;
for (var i = 0; i < collection.Count; i++)
{
var key = keys[i];
var values = collection.GetValues(key);
if (values == null)
continue;
foreach (var value in values)
{
if (!string.IsNullOrEmpty(key))
{
sb.Append(key).Append('=');
}
sb.Append(HttpUtility.UrlEncode(value)).Append('&');
}
}
return sb.ToString(0, sb.Length - 1);
}
public static byte[] Base64StringToBytes(string base64String)
{
var buffer = new byte[
(base64String.Length * 3 + 3) / 4
- (
base64String.Length > 0 && base64String[^1] == '='
? base64String.Length > 1 && base64String[^2] == '='
? 2
: 1
: 0
)
];
return Convert.TryFromBase64String(base64String, buffer, out _) ? buffer : [];
}
public static string ToSha256Hash(string input)
{
var hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(hashBytes).Replace("-", "");
}
}
上述代码是一个 C# 类库,主要用于 ASP.NET Core 应用程序的扩展和实用功能。以下是代码中各个部分的功能解释:
DpzAppBuilderExtensions
类这是一个静态类,包含了一系列扩展方法,用于增强 IApplicationBuilder
和其他类型的功能。
Init
方法Date
类型的 BSON 序列化器。GetHostingEnvironment
方法获取当前的 Web 主机环境信息。HandlerOtherStatusCode
方法处理非 200 状态码的响应。HandlerOtherStatusCode
方法UseStatusCodePages
中间件来处理状态码。NotFound.html
)。GetHostingEnvironment
方法IWebHostEnvironment
服务中获取信息,并将其存储在 EnvironmentInfo
类中。GenerateMd5
和 GenerateHashMd5
: 生成字符串的 MD5 哈希值。ToSha256Hash
: 生成字符串的 SHA256 哈希值。ToTimeStamp
: 将 DateTime
转换为 Unix 时间戳(秒)。ToDateTime
: 将 Unix 时间戳转换为 DateTime
。ForEach
: 遍历集合并对每个元素执行指定的操作。IndexOf
: 获取集合中指定元素的索引。ToImages
和 ToObjectIdImages
: 从 HTML 集合中提取所有图片的 src
属性,并将其转换为字符串或 ObjectId
列表。ReplaceOne
: 只替换字符串中第一次出现的指定子字符串。WildCardMatch
: 使用通配符匹配字符串。ToQueryString
: 将 NameValueCollection
转换为查询字符串格式。Base64StringToBytes
: 将 Base64 字符串转换为字节数组。这个类库提供了一系列实用的扩展方法,旨在简化 ASP.NET Core 应用程序的开发过程,包括状态码处理、环境信息获取、字符串和集合操作、哈希生成、时间戳转换等功能。这些方法可以帮助开发人员更高效地处理常见的编程任务。