网站首页 网站源码
website
站点相关全部源代码,隐藏了一些关于服务器的信息
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)
    {
        using var md5 = MD5.Create();
        var result = string.Join("",
            from x in md5.ComputeHash(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;
    }

    public static List<EnumInfo> EnumInfos(this System.Enum e)
    {
        var fields = e.GetType().GetFields();
        var result =
            from x in fields
            let attr = x.GetCustomAttributes(false)
                .OfType<EnumDescriptionAttribute>()
                .FirstOrDefault()
            where x.IsPublic && attr != null
            select new EnumInfo {Value = (System.Enum) x.GetValue(e), Description = attr.Description};
        return result.ToList();
    }

    /// <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.Any())
            .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.Any())
            .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);
    }
}
loading