Skip to content

Instantly share code, notes, and snippets.

@IllyaTheHath
Last active April 30, 2020 11:47
Show Gist options
  • Save IllyaTheHath/5f3c041cc81300b5c0e7562af6dce1e3 to your computer and use it in GitHub Desktop.
Save IllyaTheHath/5f3c041cc81300b5c0e7562af6dce1e3 to your computer and use it in GitHub Desktop.
Extension Methods
//
// Author: @IllyaTheHath
// Licensed under the MIT license
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace KC.Helper
{
/// <summary>
/// 参数校验辅助类
/// </summary>
public static class ArgumentHelper
{
#region Null/Empty Checking
public static void CheckIfNull(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
}
public static void CheckIfNullOrEmpty(String value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (String.IsNullOrEmpty(value))
{
throw new ArgumentException($"{nameof(value)} cannot be an empty string.");
}
}
public static void CheckIfNullOrWhitespace(String value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Length == 0)
{
throw new ArgumentException($"{nameof(value)} cannot be an empty string.");
}
if (String.IsNullOrWhiteSpace(value))
{
throw new ArgumentException($"{nameof(value)} cannot consist entirely of whitespace.");
}
}
public static void CheckIfIfNullOrEmpty(Array array)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Length == 0)
{
throw new ArgumentException($"{nameof(array)} cannot be an empty array.");
}
}
public static void CheckIfIfNullOrEmpty<T>(IEnumerable<T> array)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Count() == 0)
{
throw new ArgumentException($"{nameof(array)} cannot be an empty list.");
}
}
#endregion Null/Empty Checking
#region Range Checking
public static void CheckIfOutOfRange(Enum value)
{
Type enumType = value.GetType();
if (!Enum.IsDefined(enumType, value))
{
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(value)} is not a valid {enumType.Name} value.");
}
}
public static void CheckIfOutOfRange<T>(T value, T min, T max) where T : IComparable
{
if (value != null)
{
if (min != null && value.CompareTo(min) < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(value)} is out of range.");
}
if (max != null && value.CompareTo(max) > 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(value)} is out of range.");
}
}
}
#endregion Range Checking
}
}
//
// Author: @IllyaTheHath
// Licensed under the MIT license
//
using System;
using System.Security.Cryptography;
using System.Text;
namespace KC.Helper
{
/// <summary>
/// 加密辅助类
/// </summary>
public static class EncryptHelper
{
#region Md5
public static String Md5(String input)
{
using (MD5 md5 = MD5.Create())
{
Byte[] bytes = Encoding.UTF8.GetBytes(input);
Byte[] hash = md5.ComputeHash(bytes);
StringBuilder sb = new StringBuilder();
for (Int32 i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}
/// <summary>
/// md5(md5(input) +salt)
/// </summary>
/// <param name="input"></param>
/// <param name="salt"></param>
/// <returns></returns>
public static String DoubleMd5(String input, String salt)
{
return Md5(Md5(input) + salt);
}
#endregion Md5
#region Base64
public static String Base64Encrypt(String input)
{
return Base64Encrypt(input, Encoding.UTF8);
}
public static String Base64Encrypt(String input, Encoding encoding)
{
return Convert.ToBase64String(encoding.GetBytes(input));
}
public static String Base64Decrypt(String input)
{
return Base64Decrypt(input, Encoding.UTF8);
}
public static String Base64Decrypt(String input, Encoding encoding)
{
return encoding.GetString(Convert.FromBase64String(input));
}
#endregion Base64
}
}
//
// Author: @IllyaTheHath
// Licensed under the MIT license
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using KC.Extension;
namespace KC.Helper
{
/// <summary>
/// HttpClient 网络请求辅助类
/// </summary>
public static class HttpHelper
{
#region get
/// <summary>
/// 以get方式同步获取字符串
/// </summary>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static String HttpGetString(
String url,
Dictionary<String, String> parameters = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
ArgumentHelper.CheckIfIfNullOrEmpty(url);
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
if (parameters.IsNotEmpty())
{
if (!url.Contains("?"))
{
url += "?";
}
foreach (var parame in parameters)
{
url += $"{ parame.Key}={parame.Value}&";
}
url = url.Substring(0, url.Length - 1);
}
HttpResponseMessage response = client.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
/// <summary>
/// 以get方式异步获取字符串
/// </summary>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<String> HttpGetStringAsync(
String url,
Dictionary<String, String> parameters = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
if (parameters.IsNotEmpty())
{
if (!url.Contains("?"))
{
url += "?";
}
foreach (var parame in parameters)
{
url += $"{ parame.Key}={parame.Value}&";
}
url = url.Substring(0, url.Length - 1);
}
HttpResponseMessage response = await client.GetAsync(url);
return await response.Content.ReadAsStringAsync();
}
}
/// <summary>
/// 以get方式同步获取流
/// </summary>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static Stream HttpGetStream(
String url,
Dictionary<String, String> parameters = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
ArgumentHelper.CheckIfIfNullOrEmpty(url);
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
if (parameters.IsNotEmpty())
{
if (!url.Contains("?"))
{
url += "?";
}
foreach (var parame in parameters)
{
url += $"{ parame.Key}={parame.Value}&";
}
url = url.Substring(0, url.Length - 1);
}
HttpResponseMessage response = client.GetAsync(url).Result;
return response.Content.ReadAsStreamAsync().Result;
}
}
/// <summary>
/// 以get方式异步获取流
/// </summary>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<Stream> HttpGetStreamAsync(
String url,
Dictionary<String, String> parameters = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
if (parameters.IsNotEmpty())
{
if (!url.Contains("?"))
{
url += "?";
}
foreach (var parame in parameters)
{
url += $"{ parame.Key}={parame.Value}&";
}
url = url.Substring(0, url.Length - 1);
}
HttpResponseMessage response = await client.GetAsync(url);
return await response.Content.ReadAsStreamAsync();
}
}
/// <summary>
/// 以get方式同步获取字节
/// </summary>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static Byte[] HttpGetBytes(
String url,
Dictionary<String, String> parameters = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
ArgumentHelper.CheckIfIfNullOrEmpty(url);
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
if (parameters.IsNotEmpty())
{
if (!url.Contains("?"))
{
url += "?";
}
foreach (var parame in parameters)
{
url += $"{ parame.Key}={parame.Value}&";
}
url = url.Substring(0, url.Length - 1);
}
HttpResponseMessage response = client.GetAsync(url).Result;
return response.Content.ReadAsByteArrayAsync().Result;
}
}
/// <summary>
/// 以get方式异步获取字节
/// </summary>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<Byte[]> HttpGetBytesAsync(
String url,
Dictionary<String, String> parameters = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
if (parameters.IsNotEmpty())
{
if (!url.Contains("?"))
{
url += "?";
}
foreach (var parame in parameters)
{
url += $"{ parame.Key}={parame.Value}&";
}
url = url.Substring(0, url.Length - 1);
}
HttpResponseMessage response = await client.GetAsync(url);
return await response.Content.ReadAsByteArrayAsync();
}
}
/// <summary>
/// 以get方式同步获取字符串并Json反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static T HttpGetJsonEntity<T>(
String url,
Dictionary<String, String> parameters = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
return HttpGetString(url, parameters, timeout, contentType, headers).DeserializeJsonToObject<T>();
}
/// <summary>
/// 以get方式异步获取字符串并Json反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<T> HttpGetJsonEntityAsync<T>(
String url,
Dictionary<String, String> parameters = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
var res = await HttpGetStringAsync(url, parameters, timeout, contentType, headers);
return res.DeserializeJsonToObject<T>();
}
#endregion get
#region post no data
/// <summary>
/// 以post方式同步获取字符串,无数据
/// </summary>
/// <param name="url"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static String HttpPostAndGetString(
String url,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
ArgumentHelper.CheckIfIfNullOrEmpty(url);
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpResponseMessage response = client.PostAsync(url, null).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
/// <summary>
/// 以post方式异步获取字符串,无数据
/// </summary>
/// <param name="url"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<String> HttpPostAndGetStringAsync(
String url,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpResponseMessage response = await client.PostAsync(url, null);
return await response.Content.ReadAsStringAsync();
}
}
#endregion post no data
#region post pair data
/// <summary>
/// 以post方式同步获取字符串
/// </summary>
/// <param name="url"></param>
/// <param name="datas"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static String HttpPostAndGetString(
String url,
Dictionary<String, String> datas = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
ArgumentHelper.CheckIfIfNullOrEmpty(url);
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (datas.IsNotEmpty())
{
content = new FormUrlEncodedContent(datas);
}
HttpResponseMessage response = client.PostAsync(url, content).Result;
content.Dispose();
return response.Content.ReadAsStringAsync().Result;
}
}
/// <summary>
/// 以post方式异步获取字符串
/// </summary>
/// <param name="url"></param>
/// <param name="datas"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<String> HttpPostAndGetStringAsync(
String url,
Dictionary<String, String> datas = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (datas.IsNotEmpty())
{
content = new FormUrlEncodedContent(datas);
}
HttpResponseMessage response = await client.PostAsync(url, content);
content.Dispose();
return await response.Content.ReadAsStringAsync();
}
}
/// <summary>
/// 以post方式同步获取流
/// </summary>
/// <param name="url"></param>
/// <param name="datas"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static Stream HttpPostAndGetStream(
String url,
Dictionary<String, String> datas = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
ArgumentHelper.CheckIfIfNullOrEmpty(url);
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (datas.IsNotEmpty())
{
content = new FormUrlEncodedContent(datas);
}
HttpResponseMessage response = client.PostAsync(url, content).Result;
content.Dispose();
return response.Content.ReadAsStreamAsync().Result;
}
}
/// <summary>
/// 以post方式异步获取流
/// </summary>
/// <param name="url"></param>
/// <param name="datas"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<Stream> HttpPostAndGetStreamAsync(
String url,
Dictionary<String, String> datas = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (datas.IsNotEmpty())
{
content = new FormUrlEncodedContent(datas);
}
HttpResponseMessage response = await client.PostAsync(url, content);
content.Dispose();
return await response.Content.ReadAsStreamAsync();
}
}
/// <summary>
/// 以post方式同步获取字节
/// </summary>
/// <param name="url"></param>
/// <param name="datas"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static Byte[] HttpPostAndGetBytes(
String url,
Dictionary<String, String> datas = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
ArgumentHelper.CheckIfIfNullOrEmpty(url);
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (datas.IsNotEmpty())
{
content = new FormUrlEncodedContent(datas);
}
HttpResponseMessage response = client.PostAsync(url, content).Result;
content.Dispose();
return response.Content.ReadAsByteArrayAsync().Result;
}
}
/// <summary>
/// 以post方式异步获取字节
/// </summary>
/// <param name="url"></param>
/// <param name="datas"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<Byte[]> HttpPostAndGetBytesAsync(
String url,
Dictionary<String, String> datas = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (datas.IsNotEmpty())
{
content = new FormUrlEncodedContent(datas);
}
HttpResponseMessage response = await client.PostAsync(url, content);
content.Dispose();
return await response.Content.ReadAsByteArrayAsync();
}
}
/// <summary>
/// 以post方式同步获取字符串并反json序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static T HttpPostAndGetJsonEntity<T>(
String url,
Dictionary<String, String> parameters = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
return HttpPostAndGetString(url, parameters, timeout, contentType, headers).DeserializeJsonToObject<T>();
}
/// <summary>
/// 以post方式异步获取字符串并json反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<T> HttpPostAndGetJsonEntityAsync<T>(
String url,
Dictionary<String, String> parameters = null,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
var res = await HttpPostAndGetStringAsync(url, parameters, timeout, contentType, headers);
return res.DeserializeJsonToObject<T>();
}
#endregion post pair data
#region post string data
/// <summary>
/// 以post方式同步获取字符串
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static String HttpPostAndGetString(
String url,
String data,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
ArgumentHelper.CheckIfIfNullOrEmpty(url);
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (!data.IsNullOrEmpty())
{
content = new StringContent(data, Encoding.UTF8, "application/json");
}
HttpResponseMessage response = client.PostAsync(url, content).Result;
content.Dispose();
return response.Content.ReadAsStringAsync().Result;
}
}
/// <summary>
/// 以post方式异步获取字符串
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<String> HttpPostAndGetStringAsync(
String url,
String data,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (!data.IsNullOrEmpty())
{
content = new StringContent(data, Encoding.UTF8, "application/json");
}
HttpResponseMessage response = await client.PostAsync(url, content);
content.Dispose();
return await response.Content.ReadAsStringAsync();
}
}
/// <summary>
/// 以post方式同步获取流
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static Stream HttpPostAndGetStream(
String url,
String data,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
ArgumentHelper.CheckIfIfNullOrEmpty(url);
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (!data.IsNullOrEmpty())
{
content = new StringContent(data, Encoding.UTF8, "application/json");
}
HttpResponseMessage response = client.PostAsync(url, content).Result;
content.Dispose();
return response.Content.ReadAsStreamAsync().Result;
}
}
/// <summary>
/// 以post方式异步获取流
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<Stream> HttpPostAndGetStreamAsync(
String url,
String data,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (!data.IsNullOrEmpty())
{
content = new StringContent(data, Encoding.UTF8, "application/json");
}
HttpResponseMessage response = await client.PostAsync(url, content);
content.Dispose();
return await response.Content.ReadAsStreamAsync();
}
}
/// <summary>
/// 以post方式同步获取字节
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static Byte[] HttpPostAndGetBytes(
String url,
String data,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
ArgumentHelper.CheckIfIfNullOrEmpty(url);
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (!data.IsNullOrEmpty())
{
content = new StringContent(data, Encoding.UTF8, "application/json");
}
HttpResponseMessage response = client.PostAsync(url, content).Result;
content.Dispose();
return response.Content.ReadAsByteArrayAsync().Result;
}
}
/// <summary>
/// 以post方式异步获取字节
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<Byte[]> HttpPostAndGetBytesAsync(
String url,
String data,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType.IsNotNull())
{
client.DefaultRequestHeaders.Add("ContentType", contentType);
}
if (headers.IsNotEmpty())
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
HttpContent content = null;
if (!data.IsNullOrEmpty())
{
content = new StringContent(data, Encoding.UTF8, "application/json");
}
HttpResponseMessage response = await client.PostAsync(url, content);
content.Dispose();
return await response.Content.ReadAsByteArrayAsync();
}
}
/// <summary>
/// 以post方式同步获取字符串并反json序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static T HttpPostAndGetJsonEntity<T>(
String url,
String data,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
return HttpPostAndGetString(url, data, timeout, contentType, headers).DeserializeJsonToObject<T>();
}
/// <summary>
/// 以post方式异步获取字符串并json反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="timeout"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<T> HttpPostAndGetJsonEntityAsync<T>(
String url,
String data,
Int32 timeout = 60,
String contentType = "application/json",
Dictionary<String, String> headers = null)
{
var res = await HttpPostAndGetStringAsync(url, data, timeout, contentType, headers);
return res.DeserializeJsonToObject<T>();
}
#endregion post string data
}
}
//
// Author: @IllyaTheHath
// Licensed under the MIT license
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace KC.Extension
{
public static class ListEx
{
public static Boolean IsNullOrEmpty<T>(this IEnumerable<T> list)
{
if (list != null && list.Count() > 0)
{
return false;
}
return true;
}
public static Boolean IsNotEmpty<T>(this IEnumerable<T> list)
{
if (list != null && list.Count() > 0)
{
return true;
}
return false;
}
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (T element in source)
action(element);
}
public static IEnumerable<T> Action<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (T element in source)
{
action(element);
yield return element;
}
}
}
}
//
// Author: @IllyaTheHath
// Licensed under the MIT license
//
using System;
using Newtonsoft.Json;
namespace KC.Extension
{
public static class ObjectEx
{
public static String ToJson(this Object obj, Formatting formatting = Formatting.None)
{
return JsonConvert.SerializeObject(obj, formatting);
}
public static Boolean IsNull(this Object obj)
{
return obj == null;
}
public static Boolean IsNotNull(this Object obj)
{
return obj != null;
}
}
}
//
// Author: @IllyaTheHath
// Licensed under the MIT license
//
using System;
using System.Text;
using System.Text.RegularExpressions;
using KC.Helper;
using Newtonsoft.Json;
namespace KC.Extension
{
public static class StringEx
{
#region 数据类型检查
/// <summary>
/// 是否为有效的Int16类型值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsInt16(this String val)
{
return Int16.TryParse(val, out _);
}
/// <summary>
/// 是否为有效的Int32类型值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsInt32(this String val)
{
return Int32.TryParse(val, out _);
}
/// <summary>
/// 是否为有效的Int32类型值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsInt(this String val)
{
return IsInt32(val);
}
/// <summary>
/// 是否为有效的Int64类型值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsInt64(this String val)
{
return Int64.TryParse(val, out _);
}
/// <summary>
/// 是否为有效的Double类型值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsDouble(this String val)
{
return Double.TryParse(val, out _);
}
/// <summary>
/// 是否为有效的Single类型值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsSingle(this String val)
{
return Single.TryParse(val, out _);
}
/// <summary>
/// 是否为有效的Single类型值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsFloat(this String val)
{
return IsSingle(val);
}
/// <summary>
/// 是否为有效的Decimal类型值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsDecimal(this String val)
{
return Decimal.TryParse(val, out _);
}
/// <summary>
/// 是否为有效的DateTime类型值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsDateTime(this String val)
{
return DateTime.TryParse(val, out _);
}
#endregion 数据类型检查
#region 数据类型转换
/// <summary>
/// 将字符串转换为等效的Int16类型数值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Int16 ToInt16(this String val)
{
Int16.TryParse(val, out var num);
return num;
}
/// <summary>
/// 将字符串转换为等效的Int32类型数值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Int32 ToInt32(this String val)
{
Int32.TryParse(val, out var num);
return num;
}
/// <summary>
/// 将字符串转换为等效的Int32类型数值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Int32 ToInt(this String val)
{
return ToInt32(val);
}
/// <summary>
/// 将字符串转换为等效的Int64类型数值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Int64 ToInt64(this String val)
{
Int64.TryParse(val, out var num);
return num;
}
/// <summary>
/// 将字符串转换为等效的Double类型数值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Double ToDouble(this String val)
{
Double.TryParse(val, out var num);
return num;
}
/// <summary>
/// 将字符串转换为等效的Single类型数值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Single ToSingle(this String val)
{
Single.TryParse(val, out var num);
return num;
}
/// <summary>
/// 将字符串转换为等效的Single类型数值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Single ToFloat(this String val)
{
return ToSingle(val);
}
/// <summary>
/// 将字符串转换为等效的Int32类型数值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Decimal ToDecimal(this String val)
{
Decimal.TryParse(val, out var num);
return num;
}
/// <summary>
/// 将字符串转换为等效的DateTime类型数值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static DateTime ToDateTime(this String val)
{
DateTime.TryParse(val, out var num);
return num;
}
#endregion 数据类型转换
#region 空值检查
/// <summary>
/// Indicates whether the specified string is null.
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsNull(this String val)
{
return val is null;
}
/// <summary>
/// Indicates whether the specified string is null or an System.String.Empty string.
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsNullOrEmpty(this String val)
{
return String.IsNullOrEmpty(val);
}
/// <summary>
/// Indicates whether a specified string is null, empty, or consists only of white-space characters.
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsNullOrWhiteSpace(this String val)
{
return String.IsNullOrWhiteSpace(val);
}
#endregion 空值检查
#region 正则
/// <summary>
/// 是否为邮箱格式
/// </summary>
/// <param name="email"></param>
/// <returns></returns>
public static Boolean IsEmailAddress(this String email)
{
String pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
return Regex.IsMatch(email, pattern);
}
/// <summary>
/// 是否为ipv4格式
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsValidIPv4(this String val)
{
if (String.IsNullOrEmpty(val))
{
return false;
}
String pattern = @"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])";
return Regex.IsMatch(val, pattern);
}
/// <summary>
/// 是否为ipv6格式
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static Boolean IsValidIPv6(this String val)
{
if (String.IsNullOrEmpty(val))
{
return false;
}
String pattern = @"(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))";
return Regex.IsMatch(val, pattern);
}
#endregion 正则
#region Format
/// <summary>
/// Replaces one or more format items in a specified string with the string representation of a specified object.
/// </summary>
/// <param name="format">A composite format string</param>
/// <param name="arg0">The object to format.</param>
/// <returns>A copy of format in which any format items are replaced by the string representation of arg0.</returns>
/// <exception cref="ArgumentNullException">format is null.</exception>
/// <exception cref="System.FormatException"> The format item in format is invalid. -or- The index of a format item is not zero</exception>
public static String Format(this String format, Object arg0)
{
return String.Format(format, arg0);
}
/// <summary>
/// Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.
/// </summary>
/// <param name="format">A composite format string</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.</returns>
/// <exception cref="ArgumentNullException">format or args is null.</exception>
/// <exception cref="System.FormatException">format is invalid. -or- The index of a format item is less than zero, or greater than or equal to the length of the args array.</exception>
public static String Format(this String format, params Object[] args)
{
return String.Format(format, args);
}
/// <summary>
/// Replaces the format item or items in a specified string with the string representation of the corresponding object. A parameter supplies culture-specific formatting information.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="arg0">The object to format.</param>
/// <returns>A copy of format in which the format item or items have been replaced by the string representation of arg0.</returns>
/// <exception cref="ArgumentNullException">format or arg0 is null.</exception>
/// <exception cref="System.FormatException">format is invalid. -or- The index of a format item is less than zero, or greater than or equal to one.</exception>
public static String Format(this String format, IFormatProvider provider, Object arg0)
{
return String.Format(provider, format, arg0);
}
/// <summary>
/// Replaces the format items in a specified string with the string representations of corresponding objects in a specified array. A parameter supplies culture-specific formatting information.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.</returns>
/// <exception cref="ArgumentNullException">format or args is null.</exception>
/// <exception cref="System.FormatException">format is invalid. -or- The index of a format item is less than zero, or greater than or equal to the length of the args array.</exception>
public static String Format(this String format, IFormatProvider provider, params Object[] args)
{
return String.Format(provider, format, args);
}
#endregion Format
#region 加密
public static String Md5(this String val)
{
return EncryptHelper.Md5(val);
}
/// <summary>
/// md5(md5(input) +salt)
/// </summary>
/// <param name="val"></param>
/// <param name="salt"></param>
/// <returns></returns>
public static String DoubleMd5(this String val, String salt)
{
return EncryptHelper.DoubleMd5(val, salt);
}
public static String Base64Encrypt(this String val)
{
return EncryptHelper.Base64Encrypt(val);
}
public static String Base64Encrypt(this String val, Encoding encoding)
{
return EncryptHelper.Base64Encrypt(val, encoding);
}
public static String Base64Decrypt(this String val)
{
return EncryptHelper.Base64Decrypt(val);
}
public static String Base64Decrypt(this String val, Encoding encoding)
{
return EncryptHelper.Base64Decrypt(val, encoding);
}
#endregion 加密
/// <summary>
/// 反序列化Json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val"></param>
/// <returns></returns>
public static T DeserializeJsonToObject<T>(this String val)
{
T t = JsonConvert.DeserializeObject<T>(val);
return t;
}
/// <summary>
/// 反转字符串
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static String Reverse(this String val)
{
var chars = new Char[val.Length];
for (Int32 i = val.Length - 1, j = 0; i >= 0; --i, ++j)
{
chars[j] = val[i];
}
val = new String(chars);
return val;
}
public static String GetValueOrDefault(this String val, String defaultValue)
{
return !String.IsNullOrWhiteSpace(val) ? val : defaultValue;
}
/// <summary>
/// 转换为枚举类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static T ToEnum<T>(this String val, T defaultValue = default(T)) where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Type T Must of type System.Enum");
}
return Enum.TryParse(val, true, out T result) ? result : defaultValue;
}
public static Int32 Compare(this String val, String str)
{
return String.Compare(val, str);
}
public static Int32 Compare(this String val, String str, Boolean ignoreCase)
{
return String.Compare(val, str, ignoreCase);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment