20230514
This commit is contained in:
parent
ff965f08bd
commit
ef329af61a
@ -1,8 +1,4 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace anbs_cp.Classes;
|
||||
namespace anbs_cp.Classes;
|
||||
|
||||
/// <summary>
|
||||
/// Класс -- расширение для класса File
|
||||
@ -17,14 +13,6 @@ public static class FileExtension
|
||||
public static string MIMEType (string filename) =>
|
||||
MimeTypes.GetMimeType(filename);
|
||||
|
||||
/// <summary>
|
||||
/// Получает MIME-тип файла
|
||||
/// </summary>
|
||||
/// <param name="file">Загружаемый файл</param>
|
||||
/// <returns>MIME-тип файла</returns>
|
||||
public static string MIMEType (IFormFile file) =>
|
||||
file.ContentType;
|
||||
|
||||
/// <summary>
|
||||
/// Размер файла в байтах
|
||||
/// </summary>
|
||||
|
@ -1,8 +1,6 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace anbs_cp.Classes;
|
||||
|
||||
/// <summary>
|
||||
@ -23,19 +21,6 @@ public sealed class FileHash
|
||||
Hash = md5.ComputeHash(stream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение md5-хэша загружаемого файла.
|
||||
/// Взято с https://stackoverflow.com/a/67081012/16469671
|
||||
/// </summary>
|
||||
/// <param name="file">Загружаемый файл</param>
|
||||
/// <returns>Массив хэша</returns>
|
||||
public FileHash (IFormFile file)
|
||||
{
|
||||
using MD5 md5 = MD5.Create();
|
||||
using StreamReader streamReader = new(file.OpenReadStream());
|
||||
Hash = md5.ComputeHash(streamReader.BaseStream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Простой конструктор
|
||||
/// </summary>
|
||||
|
50
anbs_cp/Classes/PasswordOptions.cs
Normal file
50
anbs_cp/Classes/PasswordOptions.cs
Normal file
@ -0,0 +1,50 @@
|
||||
namespace anbs_cp.Classes;
|
||||
|
||||
/// <summary>
|
||||
/// Параметры пароля
|
||||
/// </summary>
|
||||
public sealed class PasswordOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public PasswordOptions ()
|
||||
{
|
||||
RequiredLength = 8;
|
||||
RequireLowercase = true;
|
||||
RequireUppercase = true;
|
||||
RequireDigit = true;
|
||||
RequireNonAlphanumeric = false;
|
||||
RequiredUniqueChars = 6;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Требуемая длина пароля
|
||||
/// </summary>
|
||||
public byte RequiredLength { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Требовать строчные буквы в пароле
|
||||
/// </summary>
|
||||
public bool RequireLowercase { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Требовать прописные буквы в пароле
|
||||
/// </summary>
|
||||
public bool RequireUppercase { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Требовать цифры в пароле
|
||||
/// </summary>
|
||||
public bool RequireDigit { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Требовать символы
|
||||
/// </summary>
|
||||
public bool RequireNonAlphanumeric { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Уникальных символов
|
||||
/// </summary>
|
||||
public byte RequiredUniqueChars { get; set; }
|
||||
}
|
111
anbs_cp/Classes/TextFormatter.cs
Normal file
111
anbs_cp/Classes/TextFormatter.cs
Normal file
@ -0,0 +1,111 @@
|
||||
using System.Net.Mail;
|
||||
|
||||
namespace anbs_cp.Classes;
|
||||
|
||||
/// <summary>
|
||||
/// Форматирование текста
|
||||
/// </summary>
|
||||
public static class TextFormatter
|
||||
{
|
||||
/// <summary>
|
||||
/// Заменяет %МАРКЕРЫ% на их значения
|
||||
/// </summary>
|
||||
/// <param name="message">Текст сообщения</param>
|
||||
/// <param name="replaceDictionary">Словарь замен</param>
|
||||
/// <returns>Отформатированное сообщение</returns>
|
||||
public static string FormatMessage (string message, Dictionary<string, string> replaceDictionary) =>
|
||||
replaceDictionary.Aggregate(message,
|
||||
static (current, item) => current.Replace($"%{item.Key}%", item.Value));
|
||||
|
||||
/// <summary>
|
||||
/// Обрезает строку до указанных в параметре <paramref name="maxLength"/> символов
|
||||
/// </summary>
|
||||
/// <param name="text">Текст, который нужно обрезать</param>
|
||||
/// <param name="maxLength">Максимальное количество символов в тексте</param>
|
||||
/// <param name="endDots">Чем завершать обрезанный текст, если он был обрезан. Внимание расходует <see cref="maxLength"/>!</param>
|
||||
/// <returns>Обрезанный текст</returns>
|
||||
public static string GetShortText (string text, int maxLength, string endDots = "") =>
|
||||
text.Length < maxLength ? text : $"{text[..(maxLength - endDots.Length)]}{endDots}";
|
||||
|
||||
/// <summary>
|
||||
/// Генерирует случайный пароль, удовлетворяющий параметрам <see cref="PasswordOptions"/> <paramref name="options"/>.
|
||||
/// Автор метода: Darkseal (https://stackoverflow.com/users/1233379/darkseal)
|
||||
/// URL: https://stackoverflow.com/a/46229180/16469671
|
||||
/// </summary>
|
||||
/// <param name="options">Объект допустимых параметров пароля, содержащий требования к надежности пароля.</param>
|
||||
/// <returns>Случайный пароль</returns>
|
||||
public static string GenerateRandomPassword (PasswordOptions? options)
|
||||
{
|
||||
//Проверка options и установка по-умолчанию
|
||||
options ??= new();
|
||||
|
||||
//Получаю массив символов
|
||||
string[] randomChars = {
|
||||
"ABCDEFGHJKLMNOPQRSTUVWXYZ", // прописные буквы
|
||||
"abcdefghijkmnopqrstuvwxyz", // строчные буквы
|
||||
"0123456789", // цифры
|
||||
"~!@#$%^&*+-/.,{}[]();:|?<>='`" // символы
|
||||
};
|
||||
|
||||
//Создаю объект Random
|
||||
Random rand = new(Environment.TickCount);
|
||||
|
||||
//Массив результатов
|
||||
List<char> chars = new();
|
||||
|
||||
//Вставляю прописные буквы
|
||||
if (options.RequireUppercase)
|
||||
chars.Insert(rand.Next(0, chars.Count),
|
||||
randomChars[0][rand.Next(0, randomChars[0].Length)]);
|
||||
|
||||
//Вставляю строчные буквы
|
||||
if (options.RequireLowercase)
|
||||
chars.Insert(rand.Next(0, chars.Count),
|
||||
randomChars[1][rand.Next(0, randomChars[1].Length)]);
|
||||
|
||||
//Вставляю цифры
|
||||
if (options.RequireDigit)
|
||||
chars.Insert(rand.Next(0, chars.Count),
|
||||
randomChars[2][rand.Next(0, randomChars[2].Length)]);
|
||||
|
||||
//Вставляю символы
|
||||
if (options.RequireNonAlphanumeric)
|
||||
chars.Insert(rand.Next(0, chars.Count),
|
||||
randomChars[3][rand.Next(0, randomChars[3].Length)]);
|
||||
|
||||
//Делаю выборку
|
||||
for (int i = chars.Count; i < options.RequiredLength || chars.Distinct().Count() < options.RequiredUniqueChars; i++)
|
||||
{
|
||||
string rcs = randomChars[rand.Next(0, randomChars.Length)];
|
||||
chars.Insert(rand.Next(0, chars.Count),
|
||||
rcs[rand.Next(0, rcs.Length)]);
|
||||
}
|
||||
|
||||
//Вывожу результат
|
||||
return new(chars.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Проверяет <paramref name="email"/> на соответствие критерию электронной почты
|
||||
/// Взято с: https://stackoverflow.com/a/1374644/16469671
|
||||
/// </summary>
|
||||
/// <param name="email">Проверяемая строка</param>
|
||||
/// <returns>Является ли <paramref name="email"/> адресом электронной почты</returns>
|
||||
public static bool IsValidEmail (string email)
|
||||
{
|
||||
string trimmedEmail = email.Trim();
|
||||
|
||||
if (trimmedEmail.EndsWith(".", StringComparison.Ordinal))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
MailAddress addr = new(email);
|
||||
return addr.Address == trimmedEmail;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,7 +1,4 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Html;
|
||||
|
||||
namespace anbs_cp.Classes;
|
||||
namespace anbs_cp.Classes;
|
||||
|
||||
/// <summary>
|
||||
/// Конвертер типов на манер Delphi
|
||||
@ -13,37 +10,37 @@ public static class TypeConverter
|
||||
/// <summary>
|
||||
/// Преобразование int в string
|
||||
/// </summary>
|
||||
/// <param name="AInt">Число</param>
|
||||
/// <param name="aInt">Число</param>
|
||||
/// <returns>Строка</returns>
|
||||
public static string IntToStr(int AInt) => AInt.ToString();
|
||||
public static string IntToStr (int aInt) => aInt.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// Преобразование uint в string
|
||||
/// </summary>
|
||||
/// <param name="AInt">Число</param>
|
||||
/// <param name="aInt">Число</param>
|
||||
/// <returns>Строка</returns>
|
||||
public static string IntToStr(uint AInt) => AInt.ToString();
|
||||
public static string IntToStr (uint aInt) => aInt.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// Преобразование long в string
|
||||
/// </summary>
|
||||
/// <param name="AInt">Число</param>
|
||||
/// <param name="aInt">Число</param>
|
||||
/// <returns>Строка</returns>
|
||||
public static string IntToStr(long AInt) => AInt.ToString();
|
||||
public static string IntToStr (long aInt) => aInt.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// Преобразование ulong в string
|
||||
/// </summary>
|
||||
/// <param name="AInt">Число</param>
|
||||
/// <param name="aInt">Число</param>
|
||||
/// <returns>Строка</returns>
|
||||
public static string IntToStr(ulong AInt) => AInt.ToString();
|
||||
public static string IntToStr (ulong aInt) => aInt.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// Преобразование byte в string
|
||||
/// </summary>
|
||||
/// <param name="AInt">Число</param>
|
||||
/// <param name="aInt">Число</param>
|
||||
/// <returns>Строка</returns>
|
||||
public static string IntToStr(byte AInt) => AInt.ToString();
|
||||
public static string IntToStr (byte aInt) => aInt.ToString();
|
||||
|
||||
#endregion
|
||||
|
||||
@ -52,86 +49,67 @@ public static class TypeConverter
|
||||
/// <summary>
|
||||
/// Преобразование строки в число
|
||||
/// </summary>
|
||||
/// <param name="AStr">Строка</param>
|
||||
/// <param name="ADefault">Значение по умолчанию (по умолчанию, 0)</param>
|
||||
/// <param name="aStr">Строка</param>
|
||||
/// <param name="aDefault">Значение по умолчанию (по умолчанию, 0)</param>
|
||||
/// <returns>Число</returns>
|
||||
public static int StrToInt(string AStr, int ADefault = 0)
|
||||
public static int StrToInt (string aStr, int aDefault = 0)
|
||||
{
|
||||
if (!int.TryParse(AStr, out int result)) result = ADefault;
|
||||
if (!int.TryParse(aStr, out int result))
|
||||
result = aDefault;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Преобразование строки в число
|
||||
/// </summary>
|
||||
/// <param name="AStr">Строка</param>
|
||||
/// <param name="ADefault">Значение по умолчанию (по умолчанию, 0)</param>
|
||||
/// <param name="aStr">Строка</param>
|
||||
/// <param name="aDefault">Значение по умолчанию (по умолчанию, 0)</param>
|
||||
/// <returns>Число</returns>
|
||||
public static uint StrToUInt(string AStr, uint ADefault = 0)
|
||||
public static uint StrToUInt (string aStr, uint aDefault = 0)
|
||||
{
|
||||
if (!uint.TryParse(AStr, out uint result)) result = ADefault;
|
||||
if (!uint.TryParse(aStr, out uint result))
|
||||
result = aDefault;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Преобразование строки в число
|
||||
/// </summary>
|
||||
/// <param name="AStr">Строка</param>
|
||||
/// <param name="ADefault">Значение по умолчанию (по умолчанию, 0)</param>
|
||||
/// <param name="aStr">Строка</param>
|
||||
/// <param name="aDefault">Значение по умолчанию (по умолчанию, 0)</param>
|
||||
/// <returns>Число</returns>
|
||||
public static long StrToInt64(string AStr, long ADefault = 0)
|
||||
public static long StrToInt64 (string aStr, long aDefault = 0)
|
||||
{
|
||||
if (!long.TryParse(AStr, out long result)) result = ADefault;
|
||||
if (!long.TryParse(aStr, out long result))
|
||||
result = aDefault;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Преобразование строки в число
|
||||
/// </summary>
|
||||
/// <param name="AStr">Строка</param>
|
||||
/// <param name="ADefault">Значение по умолчанию (по умолчанию, 0)</param>
|
||||
/// <param name="aStr">Строка</param>
|
||||
/// <param name="aDefault">Значение по умолчанию (по умолчанию, 0)</param>
|
||||
/// <returns>Число</returns>
|
||||
public static ulong StrToUInt64(string AStr, ulong ADefault = 0)
|
||||
public static ulong StrToUInt64 (string aStr, ulong aDefault = 0)
|
||||
{
|
||||
if (!ulong.TryParse(AStr, out ulong result)) result = ADefault;
|
||||
if (!ulong.TryParse(aStr, out ulong result))
|
||||
result = aDefault;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Преобразование строки в число
|
||||
/// </summary>
|
||||
/// <param name="AStr">Строка</param>
|
||||
/// <param name="ADefault">Значение по умолчанию (по умолчанию, 0)</param>
|
||||
/// <param name="aStr">Строка</param>
|
||||
/// <param name="aDefault">Значение по умолчанию (по умолчанию, 0)</param>
|
||||
/// <returns>Число</returns>
|
||||
public static byte StrToByte(string AStr, byte ADefault = 0)
|
||||
public static byte StrToByte (string aStr, byte aDefault = 0)
|
||||
{
|
||||
if (!byte.TryParse(AStr, out byte result)) result = ADefault;
|
||||
if (!byte.TryParse(aStr, out byte result))
|
||||
result = aDefault;
|
||||
return result;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Конвернтация IHtmlContent
|
||||
/// <summary>
|
||||
/// Преобразует тип <see cref="IHtmlContent"/> в строку <see cref="string"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">Значение, которое нужно преобразовать.</param>
|
||||
/// <returns><see cref="string"/></returns>
|
||||
public static string HtmlContentToString(IHtmlContent content)
|
||||
{
|
||||
//Создаём writer
|
||||
using StringWriter writer = new();
|
||||
//Конвертируем IHtmlContent в string
|
||||
content.WriteTo(writer, HtmlEncoder.Default);
|
||||
//Возвращаем результат
|
||||
return writer.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Преобразует строку <see cref="string"/> в тип <see cref="IHtmlContent"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">Значение, которое нужно преобразовать.</param>
|
||||
/// <returns><see cref="IHtmlContent"/></returns>
|
||||
public static IHtmlContent StringToHtmlContent(string content) => new HtmlContentBuilder().AppendHtml(content);
|
||||
#endregion
|
||||
}
|
@ -2,11 +2,11 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<Version>2023.409.2</Version>
|
||||
<Authors>Alexander Babaev</Authors>
|
||||
<Product>ANB Software Components Pack</Product>
|
||||
<Description>Library of some useful functions in C# language.</Description>
|
||||
<Copyright>Alexander Babaev</Copyright>
|
||||
<Version>2023.0514.2</Version>
|
||||
<Authors>Александр Бабаев</Authors>
|
||||
<Product>Набор компонентов ANB Software</Product>
|
||||
<Description>Библиотека полезных методов языка C#</Description>
|
||||
<Copyright>Александр Бабаев</Copyright>
|
||||
<AssemblyName>anbs_cp</AssemblyName>
|
||||
<RootNamespace>anbs_cp</RootNamespace>
|
||||
<Nullable>enable</Nullable>
|
||||
@ -38,10 +38,8 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="gfoidl.Base64" Version="2.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="5.0.17" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Shell.Interop" Version="17.5.33428.366" />
|
||||
<PackageReference Include="Microsoft.Windows.Compatibility" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Windows.Compatibility" Version="7.0.1" />
|
||||
<PackageReference Include="MimeTypes" Version="2.4.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
|
17
anbs_cpfn/Classes/NetFileExtension.cs
Normal file
17
anbs_cpfn/Classes/NetFileExtension.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace anbs_cp.ForNet.Classes;
|
||||
|
||||
/// <summary>
|
||||
/// Класс -- расширение для класса File
|
||||
/// </summary>
|
||||
public class NetFileExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// Получает MIME-тип файла
|
||||
/// </summary>
|
||||
/// <param name="file">Загружаемый файл</param>
|
||||
/// <returns>MIME-тип файла</returns>
|
||||
public static string MIMEType (IFormFile file) =>
|
||||
file.ContentType;
|
||||
}
|
38
anbs_cpfn/Classes/NetFileHash.cs
Normal file
38
anbs_cpfn/Classes/NetFileHash.cs
Normal file
@ -0,0 +1,38 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
using anbs_cp.Classes;
|
||||
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace anbs_cp.ForNet.Classes;
|
||||
|
||||
public static class NetFileHash
|
||||
{
|
||||
/// <summary>
|
||||
/// Получение md5-хэша загружаемого файла.
|
||||
/// Взято с https://stackoverflow.com/a/67081012/16469671
|
||||
/// </summary>
|
||||
/// <param name="file">Загружаемый файл</param>
|
||||
/// <returns>Массив хэша</returns>
|
||||
public static FileHash GetFileHash (IFormFile file)
|
||||
{
|
||||
//Создаю md5
|
||||
using MD5 md5 = MD5.Create();
|
||||
|
||||
//Создаю поток для чтения
|
||||
using StreamReader streamReader = new(file.OpenReadStream());
|
||||
|
||||
//Получаю строковый хэш
|
||||
string hash = BitConverter.ToString(md5.ComputeHash(streamReader.BaseStream)).Replace("-", "")
|
||||
.ToLowerInvariant();
|
||||
|
||||
//Создаю результат
|
||||
FileHash fileHash = new();
|
||||
|
||||
//Вношу в него данные
|
||||
fileHash.FromString(hash);
|
||||
|
||||
//Возвращаю результат
|
||||
return fileHash;
|
||||
}
|
||||
}
|
35
anbs_cpfn/Classes/NetTypeConverter.cs
Normal file
35
anbs_cpfn/Classes/NetTypeConverter.cs
Normal file
@ -0,0 +1,35 @@
|
||||
using System.Text.Encodings.Web;
|
||||
|
||||
using Microsoft.AspNetCore.Html;
|
||||
|
||||
namespace anbs_cp.ForNet.Classes;
|
||||
|
||||
/// <summary>
|
||||
/// Расширение конвертера типов на манер Delphi
|
||||
/// </summary>
|
||||
public static class NetTypeConverter
|
||||
{
|
||||
#region Конвернтация IHtmlContent
|
||||
/// <summary>
|
||||
/// Преобразует тип <see cref="IHtmlContent"/> в строку <see cref="string"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">Значение, которое нужно преобразовать.</param>
|
||||
/// <returns><see cref="string"/></returns>
|
||||
public static string HtmlContentToString(IHtmlContent content)
|
||||
{
|
||||
//Создаём writer
|
||||
using StringWriter writer = new();
|
||||
//Конвертируем IHtmlContent в string
|
||||
content.WriteTo(writer, HtmlEncoder.Default);
|
||||
//Возвращаем результат
|
||||
return writer.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Преобразует строку <see cref="string"/> в тип <see cref="IHtmlContent"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">Значение, которое нужно преобразовать.</param>
|
||||
/// <returns><see cref="IHtmlContent"/></returns>
|
||||
public static IHtmlContent StringToHtmlContent(string content) => new HtmlContentBuilder().AppendHtml(content);
|
||||
#endregion
|
||||
}
|
110
anbs_cpfn/Extensions/UrlHelperExtension.cs
Normal file
110
anbs_cpfn/Extensions/UrlHelperExtension.cs
Normal file
@ -0,0 +1,110 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
|
||||
namespace anbs_cp.ForNet.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// Расширение URLHelper
|
||||
/// </summary>
|
||||
public static class UrlHelperExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// Очищает URL, удаляя ненужные QueryString
|
||||
/// </summary>
|
||||
/// <param name="helper">
|
||||
/// <see cref="IUrlHelper" />
|
||||
/// </param>
|
||||
/// <param name="context">
|
||||
/// <see cref="HttpContext" />
|
||||
/// </param>
|
||||
/// <param name="url">Ссылка, которую нужно почистить</param>
|
||||
/// <param name="clearQueryString">Массив ключей, которые нужно удалить</param>
|
||||
/// <param name="getLocalURL">Возвращать только локальную ссылку</param>
|
||||
/// <returns></returns>
|
||||
public static string ParseURLQuery(this IUrlHelper helper, HttpContext context, string? url,
|
||||
string[] clearQueryString, bool getLocalURL = true)
|
||||
{
|
||||
//Получаю returnURL
|
||||
url ??= "/";
|
||||
|
||||
//Если адрес локальный, то преобразую в полный
|
||||
if (helper.IsLocalUrl(url))
|
||||
url = LocalToFullURL(helper, context, url);
|
||||
|
||||
//Создаю uri по адресу
|
||||
Uri uri = new(url ?? "");
|
||||
|
||||
//Формат
|
||||
const UriFormat format = UriFormat.UriEscaped;
|
||||
|
||||
//Формирую Uri-адрес сайта
|
||||
string baseUri =
|
||||
uri.GetComponents(UriComponents.Scheme | UriComponents.Host | UriComponents.Port,
|
||||
format);
|
||||
|
||||
//Формирую локальную ссылку
|
||||
string localUri = uri.GetComponents(UriComponents.Path, format);
|
||||
|
||||
//Создаю словарь запроса
|
||||
Dictionary<string, StringValues> query = QueryHelpers.ParseQuery(uri.Query);
|
||||
|
||||
//Если он содержит параметр для очистки, то удаляю его
|
||||
foreach (KeyValuePair<string, StringValues> queryItem in query.Where(queryItem =>
|
||||
clearQueryString.Contains(queryItem.Key)))
|
||||
query.Remove(queryItem.Key);
|
||||
|
||||
//Создаю список запроса, пригодный для QueryBuilder
|
||||
List<KeyValuePair<string, string>> queryList = query.Select(static queryItem =>
|
||||
new KeyValuePair<string, string>(queryItem.Key, queryItem.Value.ToString())).ToList();
|
||||
|
||||
//Запускаю построение новых параметров
|
||||
QueryBuilder qBuilder = new(queryList);
|
||||
|
||||
//Создаю переменную-результат
|
||||
string result = "";
|
||||
|
||||
//Если нужно получить полную ссылку
|
||||
if (!getLocalURL)
|
||||
result = baseUri;
|
||||
|
||||
//формирую переменную-результат
|
||||
result = $"{result}/{localUri}{qBuilder.ToQueryString()}";
|
||||
|
||||
//Вывожу результат
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получает локальный url-адрес
|
||||
/// </summary>
|
||||
/// <param name="helper"><see cref="IUrlHelper" /></param>
|
||||
/// <param name="url">url-адрес</param>
|
||||
/// <returns>Локальный url-адрес</returns>
|
||||
public static string ToLocalURL (this IUrlHelper helper, string url)
|
||||
{
|
||||
//Создаю uri из url
|
||||
Uri uri = new(url);
|
||||
|
||||
//Вывожу результат
|
||||
return helper.IsLocalUrl(url) ? url : uri.PathAndQuery;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Преобразует локальную ссылку в полную
|
||||
/// </summary>
|
||||
/// <param name="helper">
|
||||
/// <see cref="IUrlHelper" />
|
||||
/// </param>
|
||||
/// <param name="context">
|
||||
/// <see cref="HttpContext" />
|
||||
/// </param>
|
||||
/// <param name="url">Ссылка</param>
|
||||
/// <returns>
|
||||
/// <see cref="string" />
|
||||
/// </returns>
|
||||
public static string? LocalToFullURL (this IUrlHelper helper, HttpContext context, string? url) =>
|
||||
helper.IsLocalUrl(url) ? $"{context.Request.Scheme}://{context.Request.Host}{url}" : url;
|
||||
}
|
38
anbs_cpfn/anbs_cpfn.csproj
Normal file
38
anbs_cpfn/anbs_cpfn.csproj
Normal file
@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||
<PackageId>ANBSoftware.ComponentsPackForNet</PackageId>
|
||||
<Version>2023.05.14.1</Version>
|
||||
<Authors>Александр Бабаев</Authors>
|
||||
<Product>Набор компонентов ANB Software для ASP.NET Core</Product>
|
||||
<Description>Библиотека полезных методов языка C# для ASP.NET Core</Description>
|
||||
<Copyright>Александр Бабаев</Copyright>
|
||||
<PackageProjectUrl>https://git.babaev-an.ru/babaev-an/anbsoftware_componentspack</PackageProjectUrl>
|
||||
<RepositoryUrl>https://git.babaev-an.ru/babaev-an/anbsoftware_componentspack</RepositoryUrl>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
<RootNamespace>anbs_cp.ForNet</RootNamespace>
|
||||
<AssemblyName>anbs_cp_fn</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="5.0.17" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.TagHelpers" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\anbs_cp\anbs_cp.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Extensions\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -5,7 +5,12 @@ VisualStudioVersion = 17.0.31903.59
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "anbs_cp", "anbs_cp\anbs_cp.csproj", "{442A56CC-1061-4EB5-8B67-3E3D997976D7}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "demo", "demo\demo.csproj", "{3BB0778D-3C34-4DD8-A54E-CB476BEF2F7B}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "demo", "demo\demo.csproj", "{3BB0778D-3C34-4DD8-A54E-CB476BEF2F7B}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{442A56CC-1061-4EB5-8B67-3E3D997976D7} = {442A56CC-1061-4EB5-8B67-3E3D997976D7}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "anbs_cpfn", "anbs_cpfn\anbs_cpfn.csproj", "{EDED871B-8A96-4A2F-83CF-AD40FF66F6E2}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{442A56CC-1061-4EB5-8B67-3E3D997976D7} = {442A56CC-1061-4EB5-8B67-3E3D997976D7}
|
||||
EndProjectSection
|
||||
@ -23,6 +28,10 @@ Global
|
||||
{3BB0778D-3C34-4DD8-A54E-CB476BEF2F7B}.Debug|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{3BB0778D-3C34-4DD8-A54E-CB476BEF2F7B}.Debug|Any CPU.Build.0 = Release|Any CPU
|
||||
{3BB0778D-3C34-4DD8-A54E-CB476BEF2F7B}.Release|Any CPU.ActiveCfg = Debug.CNF|Any CPU
|
||||
{EDED871B-8A96-4A2F-83CF-AD40FF66F6E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{EDED871B-8A96-4A2F-83CF-AD40FF66F6E2}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{EDED871B-8A96-4A2F-83CF-AD40FF66F6E2}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{EDED871B-8A96-4A2F-83CF-AD40FF66F6E2}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
@ -4,7 +4,10 @@
|
||||
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=HDD/@EntryIndexedValue">HDD</s:String>
|
||||
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=RA/@EntryIndexedValue">RA</s:String>
|
||||
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=RAM/@EntryIndexedValue">RAM</s:String>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=abcdefghijkmnopqrstuvwxyz/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=ABCDEFGHJKLMNOPQRSTUVWXYZ/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=anbs/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Darkseal/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Glendower/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=_0412_0435_0440_043D_0451_043C/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=_0412_0438_0434_0435_043E_043A_0430_0440_0442_0430/@EntryIndexedValue">True</s:Boolean>
|
||||
|
Loading…
x
Reference in New Issue
Block a user