主頁 > .NET開發 > Masuit.Tools,一個免費的輪子

Masuit.Tools,一個免費的輪子

2020-11-10 17:41:32 .NET開發

開源地址:

https://gitee.com/masuit/Masuit.Tools

包含一些常用的操作類,大都是靜態類,加密解密,反射操作,動態編譯,權重隨機篩選演算法,簡繁轉換,分布式短id,運算式樹,linq擴展,檔案壓縮,多執行緒下載和FTP客戶端,硬體資訊,字串擴展方法,日期時間擴展操作,中國農歷,大檔案拷貝,影像裁剪,驗證碼,斷點續傳,物體映射、集合擴展等常用封裝,

建議開發環境

作業系統:Windows 10 1903及以上版本
開發工具:VisualStudio2019 v16.5及以上版本
SDK:.Net Core 3.1.0及以上版本

安裝程式包

.NET Framework ≥4.6.1

PM> Install-Package Masuit.Tools.Net

.NET Core 2.x/3.x

PM> Install-Package Masuit.Tools.Core

為工具庫注冊配置

工具庫需要用到外部配置節:

  1. EmailDomainWhiteList,郵箱校驗需要用到的白名單域名,英文逗號分隔,每個元素支持正則運算式,若未配置,則不啟用郵箱校驗白名單

  2. EmailDomainBlockList,郵箱校驗需要用到的黑名單域名,英文逗號分隔,每個元素支持正則運算式,且黑名單優先級高于白名單,若未配置,則不啟用郵箱校驗黑白名單

  3. BaiduAK,獲取IP/地理位置相關百度云APIKey,若未配置,則無法呼叫GetIPLocation以及GetPhysicalAddress相關方法

public Startup(IConfiguration configuration)
{
configuration.AddToMasuitTools(); // 若未呼叫,則默認自動嘗試加載appsettings.json
}

特色功能示例代碼

1.檢驗字串是否是Email、手機號、URL、IP地址、身份證號

bool isEmail="[email protected]".MatchEmail(); // 可在appsetting.json中添加EmailDomainWhiteList和EmailDomainBlockList配置郵箱域名黑白名單,逗號分隔,如"EmailDomainBlockList": "^\\w{1,5}@qq.com,^\\w{1,5}@163.com,^\\w{1,5}@gmail.com,^\\w{1,5}@outlook.com",
bool isInetAddress = "114.114.114.114".MatchInetAddress();
bool isUrl = "http://masuit.com".MatchUrl();
bool isPhoneNumber = "15205201520".MatchPhoneNumber();
bool isIdentifyCard = "312000199502230660".MatchIdentifyCard();// 校驗中國大陸身份證號
bool isCNPatentNumber = "200410018477.9".MatchCNPatentNumber(); // 校驗中國專利申請號或專利號,是否帶校驗位,校驗位前是否帶“.”,都可以校驗,待校驗的號碼前不要帶CN、ZL字樣的前綴

2.硬體監測(僅支持Windows)

float load = SystemInfo.CpuLoad;// 獲取CPU占用率
long physicalMemory = SystemInfo.PhysicalMemory;// 獲取物理記憶體總數
long memoryAvailable = SystemInfo.MemoryAvailable;// 獲取物理記憶體可用率
double freePhysicalMemory = SystemInfo.GetFreePhysicalMemory();// 獲取可用物理記憶體
Dictionary<string, string> diskFree = SystemInfo.DiskFree();// 獲取磁盤每個磁區可用空間
Dictionary<string, string> diskTotalSpace = SystemInfo.DiskTotalSpace();// 獲取磁盤每個磁區總大小
Dictionary<string, double> diskUsage = SystemInfo.DiskUsage();// 獲取磁盤每個磁區使用率
double temperature = SystemInfo.GetCPUTemperature();// 獲取CPU溫度
int cpuCount = SystemInfo.GetCpuCount();// 獲取CPU核心數
IList<string> ipAddress = SystemInfo.GetIPAddress();// 獲取本機所有IP地址
string localUsedIp = SystemInfo.GetLocalUsedIP();// 獲取本機當前正在使用的IP地址
IList<string> macAddress = SystemInfo.GetMacAddress();// 獲取本機所有網卡mac地址
string osVersion = SystemInfo.GetOsVersion();// 獲取作業系統版本
RamInfo ramInfo = SystemInfo.GetRamInfo();// 獲取記憶體資訊

3.大檔案操作

FileStream fs = new FileStream(@"D:\boot.vmdk", FileMode.OpenOrCreate, FileAccess.ReadWrite);
{
//fs.CopyToFile(@"D:\1.bak");//同步復制大檔案
fs.CopyToFileAsync(@"D:\1.bak");//異步復制大檔案
string md5 = fs.GetFileMD5Async().Result;//異步獲取檔案的MD5
}

4.html的防XSS處理:

string html = @"<link href='https://www.cnblogs.com/Content/font-awesome/css' rel='stylesheet'/>
<!--[if IE 7]>
<link href='https://www.cnblogs.com/Content/font-awesome-ie7.min.css' rel='stylesheet'/>
<![endif]-->
<script src='https://www.cnblogs.com/Scripts/modernizr'></script>
<div id='searchBox' role='search'>
<form action='/packages' method='get'>
<span class='user-actions'><a href='https://www.cnblogs.com/users/account/LogOff'>退出</a></span>
<input name='q' id='searchBoxInput'/>
<input id='searchBoxSubmit' type='submit' value='https://www.cnblogs.com/lyl6796910/p/Submit' />
</form>
</div>";
string s = html.HtmlSantinizerStandard();//清理后:<div><span><a href="https://www.cnblogs.com/users/account/LogOff">退出</a></span></div>

5.整理作業系統的記憶體:

Windows.ClearMemorySilent();

6.任意進制轉換

可用于生成短id,短hash等操作,純數學運算,

NumberFormater nf = new NumberFormater(36);//內置2-62進制的轉換
//NumberFormater nf = new NumberFormater("0123456789abcdefghijklmnopqrstuvwxyz");// 自定義進制字符,可用于生成驗證碼
string s36 = nf.ToString(12345678);
long num = nf.FromString("7clzi");
Console.WriteLine("12345678的36進制是:" + s36); // 7clzi
Console.WriteLine("36進制的7clzi是:" + num); // 12345678
//擴展方法形式呼叫
var bin=12345678.ToBinary(36);//7clzi
var num="7clzi".FromBinary(36);//12345678
//超大數字的進制轉換
var num = "E6186159D38CD50E0463A55E596336BD".FromBinaryBig(16);
Console.WriteLine(num); // 十進制:305849028665645097422198928560410015421
Console.WriteLine(num.ToBinary(64)); // 64進制:3C665pQUPl3whzFlVpoPqZ,22位長度
Console.WriteLine(num.ToBinary(36)); // 36進制:dmed4dkd5bhcg4qdktklun0zh,25位長度

7.納秒級性能計時器

HiPerfTimer timer = HiPerfTimer.StartNew();
for (int i = 0; i < 100000; i++)
{
//todo
}
timer.Stop();
Console.WriteLine("執行for回圈100000次耗時"+timer.Duration+"s");
double time = HiPerfTimer.Execute(() =>
{
for (int i = 0; i < 100000; i++)
{
//todo
}
});
Console.WriteLine("執行for回圈100000次耗時"+time+"s");

8.單機產生唯一有序的短id

var token=Stopwatch.GetTimestamp().ToBinary(36);
var set = new HashSet<string>();
double time = HiPerfTimer.Execute(() =>
{
for (int i = 0; i < 1000000; i++)
{
set.Add(Stopwatch.GetTimestamp().ToBinary(36));
}
});
Console.WriteLine(set.Count==1000000);//True
Console.WriteLine("產生100w個id耗時"+time+"s");//1.6639039s

9.產生分布式唯一有序短id

var sf = SnowFlake.GetInstance();
string token = sf.GetUniqueId();// rcofqodori0w
string shortId = sf.GetUniqueShortId(8);// qodw9728
var set = new HashSet<string>();
double time = HiPerfTimer.Execute(() =>
{
for (int i = 0; i < 1000000; i++)
{
set.Add(SnowFlake.GetInstance().GetUniqueId());
}
});
Console.WriteLine(set.Count == 1000000); //True
Console.WriteLine("產生100w個id耗時" + time + "s"); //2.6891495s

10.農歷轉換

ChineseCalendar.CustomHolidays.Add(DateTime.Parse("2018-12-31"),"元旦節");//自定義節假日
ChineseCalendar today = new ChineseCalendar(DateTime.Parse("2018-12-31"));
Console.WriteLine(today.ChineseDateString);// 二零一八年十一月廿五
Console.WriteLine(today.AnimalString);// 生肖:狗
Console.WriteLine(today.GanZhiDateString);// 干支:戊戌年甲子月丁酉日
Console.WriteLine(today.DateHoliday);// 獲取按公歷計算的節假日
...

11.Linq運算式樹擴展

Expression<Func<string, bool>> where1 = s => s.StartsWith("a");
Expression<Func<string, bool>> where2 = s => s.Length > 10;
Func<string, bool> func = where1.And(where2).Compile();
bool b=func("abcd12345678");//true
Expression<Func<string, bool>> where1 = s => s.StartsWith("a");
Expression<Func<string, bool>> where2 = s => s.Length > 10;
Func<string, bool> func = where1.Or(where2).Compile();
bool b=func("abc");// true

12.模版引擎

var tmp = new Template("{{name}},你好!");
tmp.Set("name", "萬金油");
string s = tmp.Render();//萬金油,你好!
var tmp = new Template("{{one}},{{two}},{{three}}");
string s = tmp.Set("one", "1").Set("two", "2").Set("three", "3").Render();// 1,2,3
var tmp = new Template("{{name}},{{greet}}!");
tmp.Set("name", "萬金油");
string s = tmp.Render();// throw 模版變數{{greet}}未被使用

13.List轉Datatable

var list = new List<MyClass>()
{
new MyClass()
{
Name = "張三",
Age = 22
},
new MyClass()
{
Name = "李四",
Age = 21
},
new MyClass()
{
Name = "王五",
Age = 28
}
};
var table = list.Select(c => new{姓名=c.Name,年齡=c.Age}).ToList().ToDataTable();// 將自動填充列姓名和年齡

14.檔案壓縮解壓

.NET Framework

MemoryStream ms = SevenZipCompressor.ZipStream(new List<string>()
{
@"D:\1.txt",
"http://ww3.sinaimg.cn/large/87c01ec7gy1fsq6rywto2j20je0d3td0.jpg",
});//壓縮成記憶體流
SevenZipCompressor.Zip(new List<string>()
{
@"D:\1.txt",
"http://ww3.sinaimg.cn/large/87c01ec7gy1fsq6rywto2j20je0d3td0.jpg",
}, zip);//壓縮成zip
SevenZipCompressor.UnRar(@"D:\Download\test.rar", @"D:\Download\");//解壓rar
SevenZipCompressor.Decompress(@"D:\Download\test.tar", @"D:\Download\");//自動識別解壓壓縮包
SevenZipCompressor.Decompress(@"D:\Download\test.7z", @"D:\Download\");

ASP.NET Core

Startup.cs

services.AddSevenZipCompressor();

建構式注入ISevenZipCompressor

private readonly ISevenZipCompressor _sevenZipCompressor;
public Test(ISevenZipCompressor sevenZipCompressor)
{
_sevenZipCompressor = sevenZipCompressor;
}

使用方式同.NET Framework版本

15.日志組件

LogManager.LogDirectory=AppDomain.CurrentDomain.BaseDirectory+"/logs";
LogManager.Event+=info =>
{
//todo:注冊一些事件操作
};
LogManager.Info("記錄一次訊息");
LogManager.Error(new Exception("例外訊息"));

16.FTP客戶端

FtpClient ftpClient = FtpClient.GetAnonymousClient("192.168.2.2");//創建一個匿名訪問的客戶端
//FtpClient ftpClient = FtpClient.GetClient("192.168.2.3","admin","123456");// 創建一個帶用戶名密碼的客戶端
ftpClient.Delete("/1.txt");// 洗掉檔案
ftpClient.Download("/test/2.txt","D:\\test\\2.txt");// 下載檔案
ftpClient.UploadFile("/test/22.txt","D:\\test\\22.txt",(sum, progress) =>
{
Console.WriteLine("已上傳:"+progress*1.0/sum);
});//上傳檔案并檢測進度
List<string> files = ftpClient.GetFiles("/");//列出ftp服務端檔案串列
...

17.多執行緒后臺下載

var mtd = new MultiThreadDownloader("https://attachments-cdn.shimo.im/yXwC4kphjVQu06rH/KeyShot_Pro_7.3.37.7z",Environment.GetEnvironmentVariable("temp"),"E:\\Downloads\\KeyShot_Pro_7.3.37.7z",8);
mtd.Configure(req =>
{
req.Referer = "https://masuit.com";
req.Headers.Add("Origin", "https://baidu.com");
});
mtd.TotalProgressChanged+=(sender, e) =>
{
var downloader = sender as MultiThreadDownloader;
Console.WriteLine("下載進度:"+downloader.TotalProgress+"%");
Console.WriteLine("下載速度:"+downloader.TotalSpeedInBytes/1024/1024+"MBps");
};
mtd.FileMergeProgressChanged+=(sender, e) =>
{
Console.WriteLine("下載完成");
};
mtd.Start();//開始下載
//mtd.Pause(); // 暫停下載
//mtd.Resume(); // 繼續下載

18.Socket客戶端操作類

var tcpClient = new TcpClient(AddressFamily.InterNetwork);
Socket socket = tcpClient.ConnectSocket(IPAddress.Any,5000);
socket.SendFile("D:\\test\\1.txt",false,i =>
{
Console.WriteLine("已發送"+i+"%");
});

19.加密解密

var enc="123456".MDString();// MD5加密
var enc="123456".MDString("abc");// MD5加鹽加密
var enc="123456".MDString2();// MD5兩次加密
var enc="123456".MDString2("abc");// MD5兩次加鹽加密
var enc="123456".MDString3();// MD5三次加密
var enc="123456".MDString3("abc");// MD5三次加鹽加密

string aes = "123456".AESEncrypt();// AES加密為密文
string s = aes.AESDecrypt(); //AES解密為明文
string aes = "123456".AESEncrypt("abc");// AES密鑰加密為密文
string s = aes.AESDecrypt("abc"); //AES密鑰解密為明文

string enc = "123456".DesEncrypt();// DES加密為密文
string s = enc.DesDecrypt(); //DES解密為明文
string enc = "123456".DesEncrypt("abcdefgh");// DES密鑰加密為密文
string s = enc.DesDecrypt("abcdefgh"); //DES密鑰解密為明文

RsaKey rsaKey = RsaCrypt.GenerateRsaKeys();// 生成RSA密鑰對
string encrypt = "123456".RSAEncrypt(rsaKey.PublicKey);// 公鑰加密
string s = encrypt.RSADecrypt(rsaKey.PrivateKey);// 私鑰解密

string s = "123".Crc32();// 生成crc32摘要
string s = "123".Crc64();// 生成crc64摘要

20.物體校驗

public class MyClass
{
[IsEmail] //可在appsetting.json中添加EmailDomainWhiteList配置郵箱域名白名單,逗號分隔
public string Email { get; set; }

[IsPhone]
public string PhoneNumber { get; set; }

[IsIPAddress]
public string IP { get; set; }

[MinValue(0, ErrorMessage = "年齡最小為0歲"), MaxValue(100, ErrorMessage = "年齡最大100歲")]
public int Age { get; set; }

[ComplexPassword]//密碼復雜度校驗
public string Password { get; set; }
}

21.HTML操作

List<string> srcs = "html".MatchImgSrcs().ToList();// 獲取html字串里所有的img標簽的src屬性
var imgTags = "html".MatchImgTags();//獲取html字串里的所有的img標簽
var str="html".RemoveHtmlTag(); // 去除html標簽
...

22.DateTime擴展

double milliseconds = DateTime.Now.GetTotalMilliseconds();// 獲取毫秒級時間戳
double microseconds = DateTime.Now.GetTotalMicroseconds();// 獲取微秒級時間戳
double nanoseconds = DateTime.Now.GetTotalNanoseconds();// 獲取納秒級時間戳
double seconds = DateTime.Now.GetTotalSeconds();// 獲取秒級時間戳
double minutes = DateTime.Now.GetTotalMinutes();// 獲取分鐘級時間戳
...

23.IP地址和URL

bool inRange = "192.168.2.2".IpAddressInRange("192.168.1.1","192.168.3.255");// 判斷IP地址是否在這個地址段里
bool isPrivateIp = "172.16.23.25".IsPrivateIP();// 判斷是否是私有地址
bool isExternalAddress = "http://baidu.com".IsExternalAddress();// 判斷是否是外網的URL

//以下需要配置baiduAK
string isp = "114.114.114.114".GetISP(); // 獲取ISP運營商資訊
PhysicsAddress physicsAddress = "114.114.114.114".GetPhysicsAddressInfo().Result;// 獲取詳細地理資訊物件
Tuple<string, List<string>> ipAddressInfo = "114.114.114.114".GetIPAddressInfo().Result;// 獲取詳細地理資訊集合

24.元素去重

var list = new List<MyClass>()
{
new MyClass()
{
Email = "[email protected]"
},
new MyClass()
{
Email = "[email protected]"
},
new MyClass()
{
Email = "[email protected]"
}
};
List<MyClass> classes = list.DistinctBy(c => c.Email).ToList();
Console.WriteLine(classes.Count==1);//True

25.列舉擴展

public enum MyEnum
{
[Display(Name = "讀")]
[Description("讀")]
Read,

[Display(Name = "寫")]
[Description("寫")]
Write
}
Dictionary<int, string> dic1 = typeof(MyEnum).GetDictionary();// 獲取列舉值和字串表示的字典映射
var dic2 = typeof(MyEnum).GetDescriptionAndValue();// 獲取字串表示和列舉值的字典映射
string desc = MyEnum.Read.GetDescription();// 獲取Description標簽
string display = MyEnum.Read.GetDisplay();// 獲取Display標簽的Name屬性
var value = https://www.cnblogs.com/lyl6796910/p/typeof(MyEnum).GetValue("Read");//獲取字串表示值對應的列舉值
string enumString = 0.ToEnumString(typeof(MyEnum));// 獲取列舉值對應的字串表示

26.定長佇列實作

LimitedQueue<string> queue = new LimitedQueue<string>(32);// 宣告一個容量為32個元素的定長佇列
ConcurrentLimitedQueue<string> queue = new ConcurrentLimitedQueue<string>(32);// 宣告一個容量為32個元素的執行緒安全的定長佇列

27.反射操作

MyClass myClass = new MyClass();
PropertyInfo[] properties = myClass.GetProperties();// 獲取屬性串列
myClass.SetProperty("Email","[email protected]");//給物件設定值

28.獲取執行緒內唯一物件

CallContext<T>.SetData("db",dbContext);//設定執行緒內唯一物件
CallContext<T>.GetData("db");//獲取執行緒內唯一物件

29.asp.net core 獲取靜態的HttpContext物件

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddStaticHttpContext();
// ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
app.UseStaticHttpContext();
// ...
}
public async Task<IActionResult> Index()
{
HttpContext context = HttpContext2.Current;
}

30.郵件發送

new Email()
{
SmtpServer = "smtp.masuit.com",// SMTP服務器
SmtpPort = 25, // SMTP服務器埠
EnableSsl = true,//使用SSL
Username = "[email protected]",// 郵箱用戶名
Password = "123456",// 郵箱密碼
Tos = "[email protected],[email protected]", //收件人
Subject = "測驗郵件",//郵件標題
Body = "你好啊",//郵件內容
}.SendAsync(s =>
{
Console.WriteLine(s);// 發送成功后的回呼
});// 異步發送郵件

31.影像的簡單處理

ImageUtilities.CompressImage(@"F:\src\1.jpg", @"F:\dest\2.jpg");//無損壓縮圖片

"base64".SaveDataUriAsImageFile();// 將Base64編碼轉換成圖片

Image image = Image.FromFile(@"D:\1.jpg");
image.MakeThumbnail(@"D:\2.jpg", 120, 80, ThumbnailCutMode.LockWidth);//生成縮略圖

Bitmap bmp = new Bitmap(@"D:\1.jpg");
Bitmap newBmp = bmp.BWPic(bmp.Width, bmp.Height);//轉換成黑白
Bitmap newBmp = bmp.CutAndResize(new Rectangle(0, 0, 1600, 900), 160, 90);//裁剪并縮放
bmp.RevPicLR(bmp.Width, bmp.Height);//左右鏡像
bmp.RevPicUD(bmp.Width, bmp.Height);//上下鏡像

32.亂數

Random rnd = new Random();
int num = rnd.StrictNext();//產生真亂數
double gauss = rnd.NextGauss(20,5);//產生正態分布的亂數

33.權重篩選功能

var data=https://www.cnblogs.com/lyl6796910/p/new List>()
{
new WeightedItem<string>("A", 1),
new WeightedItem<string>("B", 3),
new WeightedItem<string>("C", 4),
new WeightedItem<string>("D", 4),
};
var item=data.WeightedItem();//按權重選出1個元素
var list=data.WeightedItems(2);//按權重選出2個元素
var selector = new WeightedSelector<string>(new List<WeightedItem<string>>()
{
new WeightedItem<string>("A", 1),
new WeightedItem<string>("B", 3),
new WeightedItem<string>("C", 4),
new WeightedItem<string>("D", 4),
});
var item = selector.Select();//按權重選出1個元素
var list = selector.SelectMultiple(3);//按權重選出3個元素

34.EF Core支持AddOrUpdate方法

/// <summary>
/// 按Id添加或更新文章物體
/// </summary>
public override Post SavePost(Post t)
{
DataContext.Set<Post>().AddOrUpdate(t => t.Id, t);
return t;
}

35.敏感資訊掩碼

"13123456789".Mask(); // 131****5678
"[email protected]".MaskEmail(); // a****[email protected]

36.集合擴展

var list = new List<string>()
{
"1","3","3","3"
};
list.AddRangeIf(s => s.Length > 1, "1", "11"); // 將被添加元素中的長度大于1的元素添加到list
list.AddRangeIfNotContains("1", "11"); // 將被添加元素中不包含的元素添加到list
list.RemoveWhere(s => s.Length<1); // 將集合中長度小于1的元素移除
list.InsertAfter(0, "2"); // 在第一個元素之后插入
list.InsertAfter(s => s == "1", "2"); // 在元素"1"后插入
var dic = list.ToDictionarySafety(s => s); // 安全的轉換成字典型別,當鍵重復時只添加一個鍵
var dic = list.ToConcurrentDictionary(s => s); // 轉換成并發字典型別,當鍵重復時只添加一個鍵
var dic = list.ToDictionarySafety(s => s, s => s.GetHashCode()); // 安全的轉換成字典型別,當鍵重復時只添加一個鍵
dic.AddOrUpdate("4", 4); // 添加或更新鍵值對
dic.AddOrUpdate(new Dictionary<string, int>()
{
["5"] = 5,["55"]=555
}); // 批量添加或更新鍵值對
dic.AddOrUpdate("5", 6, (s, i) => 66); // 如果是添加,則值為6,若更新則值為66
dic.AddOrUpdate("5", 6, 666); // 如果是添加,則值為6,若更新則值為666
dic.AsConcurrentDictionary(); // 普通字典轉換成并發字典集合
var table=list.ToDataTable(); // 轉換成DataTable型別
table.AddIdentityColumn(); //給DataTable增加一個自增列
table.HasRows(); // 檢查DataTable 是否有資料行
table.ToList<T>(); // datatable轉List
var set = list.ToHashSet(s=>s.Name);// 轉HashSet

37.Mime型別

var mimeMapper = new MimeMapper();
var mime = mimeMapper.GetExtensionFromMime("image/jpeg"); // .jpg
var ext = mimeMapper.GetMimeFromExtension(".jpg"); // image/jpeg

38.日期時間擴展

DateTime.Now.GetTotalSeconds(); // 獲取該時間相對于1970-01-01 00:00:00的秒數
DateTime.Now.GetTotalMilliseconds(); // 獲取該時間相對于1970-01-01 00:00:00的毫秒數
DateTime.Now.GetTotalMicroseconds(); // 獲取該時間相對于1970-01-01 00:00:00的微秒數
DateTime.Now.GetTotalNanoseconds(); // 獲取該時間相對于1970-01-01 00:00:00的納秒數
var indate=DateTime.Parse("2020-8-3").In(DateTime.Parse("2020-8-2"),DateTime.Parse("2020-8-4"));//true

//時間段計算工具
var range = new DateTimeRange(DateTime.Parse("2020-8-3"), DateTime.Parse("2020-8-5"));
range.Union(DateTime.Parse("2020-8-4"), DateTime.Parse("2020-8-6")); //連接兩個時間段,結果:2020-8-3~2020-8-6
range.In(DateTime.Parse("2020-8-3"), DateTime.Parse("2020-8-6"));//判斷是否在某個時間段內,true
var (intersected,range2) = range.Intersect(DateTime.Parse("2020-8-4"), DateTime.Parse("2020-8-6"));//兩個時間段是否相交,(true,2020-8-3~2020-8-4)
range.Contains(DateTime.Parse("2020-8-3"), DateTime.Parse("2020-8-4"));//判斷是否包含某個時間段,true
...

39.流轉換

stream.SaveAsMemoryStream(); // 任意流轉換成記憶體流
stream.ToArray(); // 任意流轉換成二進制陣列

40.數值轉換

1.2345678901.Digits8(); // 將小數截斷為8位
1.23.To<int>(); // 小數轉int
1.23.To<T>(); // 小數轉T基本型別

41.簡繁轉換

var str="個體".ToTraditional(); // 轉繁體
var str="個體".ToSimplified(); // 轉簡體

Asp.Net MVC和Asp.Net Core的支持斷點續傳和多執行緒下載的ResumeFileResult

在ASP.NET Core中通過MVC/WebAPI應用程式傳輸檔案資料時使用斷點續傳以及多執行緒下載支持,

它提供了ETag標頭以及Last-Modified標頭,它還支持以下前置條件標頭:If-MatchIf-None-MatchIf-Modified-SinceIf-Unmodified-SinceIf-Range

支持 ASP.NET Core 2.0+

從.NET Core2.0開始,ASP.NET Core內部支持斷點續傳,因此只是對FileResult做了一些擴展,只留下了“Content-Disposition” Inline的一部分,所有代碼都依賴于基礎.NET類,

如何使用

.NET Framework

在你的控制器中,你可以像在FileResult一樣的方式使用它,

using Masuit.Tools.Mvc;
using Masuit.Tools.Mvc.ResumeFileResult;
private readonly MimeMapper mimeMapper=new MimeMapper(); // 推薦使用依賴注入

public ActionResult ResumeFileResult()
{
var path = Server.MapPath("~/Content/test.mp4");
return new ResumeFileResult(path, mimeMapper.GetMimeFromPath(path), Request);
}

public ActionResult ResumeFile()
{
return this.ResumeFile("~/Content/test.mp4", mimeMapper.GetMimeFromPath(path), "test.mp4");
}

public ActionResult ResumePhysicalFile()
{
return this.ResumePhysicalFile(@"D:/test.mp4", mimeMapper.GetMimeFromPath(@"D:/test.mp4"), "test.mp4");
}

Asp.Net Core

要使用ResumeFileResults,必須在Startup.csConfigureServices方法呼叫中配置服務:

using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;
public void ConfigureServices(IServiceCollection services)
{
services.AddResumeFileResult();
}

然后在你的控制器中,你可以像在FileResult一樣的方式使用它,

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/209513.html

標籤:C#

上一篇:一個 Task 不夠,又來一個 ValueTask ,真的學懵了!

下一篇:一個 Task 不夠,又來一個 ValueTask ,真的學懵了!

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more