AzureBlobDBRepository.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
  2. using TEAMModelOS.SDK.Module.AzureBlob.Container;
  3. using TEAMModelOS.SDK.Module.AzureBlob.Interfaces;
  4. using Microsoft.WindowsAzure.Storage;
  5. using Microsoft.WindowsAzure.Storage.Blob;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Net.Http.Headers;
  10. using System.Threading.Tasks;
  11. using TEAMModelOS.SDK.Helper.Security.AESCrypt;
  12. using TEAMModelOS.SDK.Context.Exception;
  13. using Microsoft.AspNetCore.Http;
  14. using TEAMModelOS.SDK.Extension.SnowFlake;
  15. using TEAMModelOS.SDK.Context.Constant;
  16. using TEAMModelOS.SDK.Helper.Common.JsonHelper;
  17. using TEAMModelOS.SDK.Helper.Security.ShaHash;
  18. using Microsoft.Extensions.Configuration;
  19. using TEAMModelOS.SDK.Context.Configuration;
  20. using Microsoft.AspNetCore.Hosting;
  21. namespace TEAMModelOS.SDK.Module.AzureBlob.Implements
  22. {
  23. public class AzureBlobDBRepository : IAzureBlobDBRepository
  24. {
  25. public CloudBlobClient blobClient;
  26. public CloudBlobContainer blobContainer;
  27. public AzureBlobOptions _options;
  28. public IConfiguration Configuration { get; }
  29. public AzureBlobDBRepository(IConfiguration configuration, IWebHostEnvironment env, AzureBlobOptions options, AzureBlobOptions azureBlobOptions)
  30. {
  31. Configuration = configuration;
  32. // BaseConfigModel.SetBaseConfig(Configuration, env.ContentRootPath, env.WebRootPath);
  33. _options = options;
  34. if (!string.IsNullOrEmpty(options.ConnectionString))
  35. {
  36. blobClient = BlobClientSingleton.getInstance(options.ConnectionString).GetBlobClient();
  37. }
  38. else { throw new BizException("请设置正确的AzureBlob文件存储配置信息!"); }
  39. }
  40. public AzureBlobDBRepository()
  41. {
  42. // _connectionString = BaseConfigModel.Configuration["AppSettings:Azure:TableStorageConnection"];
  43. }
  44. private CloudBlobContainer InitializeBlob(string container)
  45. {
  46. //https://teammodelstorage.blob.core.chinacloudapi.cn/wechatfilescontainer
  47. // Type t = typeof(T);
  48. //若要将权限设置为仅针对 blob 的公共读取访问,请将 PublicAccess 属性设置为 BlobContainerPublicAccessType.Blob。
  49. //要删除匿名用户的所有权限,请将该属性设置为 BlobContainerPublicAccessType.Off。
  50. blobContainer = blobClient.GetContainerReference(_options .Container+"/"+ container);
  51. // await blobContainer.CreateIfNotExistsAsync();
  52. // BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  53. // permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
  54. // await blobContainer.SetPermissionsAsync(permissions);
  55. return blobContainer;
  56. }
  57. public async Task<List<AzureBlobModel>> UploadFiles(IFormFile[] file,string fileSpace= "common" , bool contentTypeDefault = false)
  58. {
  59. string groupName = fileSpace+"/" +DateTime.Now.ToString("yyyyMMdd");
  60. string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
  61. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  62. blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  63. //var serviceProperties = await blobClient.GetServicePropertiesAsync();
  64. //var corsSettings = serviceProperties.Cors;
  65. //var corsRule = corsSettings.CorsRules.FirstOrDefault(
  66. // o => o.AllowedOrigins.Contains("http://localhost:3904"));//设置你自己的服务器地址
  67. //if (corsRule == null)
  68. //{
  69. // //Add a new rule.
  70. // corsRule = new CorsRule()
  71. // {
  72. // AllowedHeaders = new List<string> { "x-ms-*", "content-type", "accept" },
  73. // AllowedMethods = CorsHttpMethods.Put| CorsHttpMethods.Head | CorsHttpMethods.Post | CorsHttpMethods.Merge | CorsHttpMethods.Get,//Since we'll only be calling Put Blob, let's just allow PUT verb
  74. // AllowedOrigins = new List<string> { "http://localhost:3904" },//This is the URL of our application.
  75. // ExposedHeaders = { },
  76. // MaxAgeInSeconds = 1 * 60 * 60,//Let the browswer cache it for an hour
  77. // };
  78. // corsSettings.CorsRules.Add(corsRule);
  79. // //Save the rule
  80. // await blobClient.SetServicePropertiesAsync(serviceProperties);
  81. //}
  82. StorageUri url = blobContainer.StorageUri;
  83. List<AzureBlobModel> list = new List<AzureBlobModel>();
  84. foreach (FormFile f in file)
  85. {
  86. string[] names = f.FileName.Split(".");
  87. string name = "";
  88. for (int i = 0; i < names.Length-1; i++) {
  89. name = name + names[i];
  90. }
  91. if (names.Length <= 1)
  92. {
  93. name = f.FileName + "_" + newFileName;
  94. }
  95. else {
  96. name = name + "_" + newFileName + "." + names[names.Length - 1];
  97. }
  98. string fileext = f.FileName.Substring(f.FileName.LastIndexOf(".")>0? f.FileName.LastIndexOf("."):0);
  99. var parsedContentDisposition = ContentDispositionHeaderValue.Parse(f.ContentDisposition);
  100. var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  101. var blockBlob = blobContainer.GetBlockBlobReference(name);
  102. if (!contentTypeDefault) {
  103. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  104. if (!string.IsNullOrEmpty(content_type))
  105. {
  106. blockBlob.Properties.ContentType = content_type;
  107. }
  108. }
  109. await blockBlob.UploadFromStreamAsync(f.OpenReadStream());
  110. string sha1= ShaHashHelper.GetSHA1(f.OpenReadStream());
  111. AzureBlobModel model = new AzureBlobModel(f, _options.Container, groupName, name)
  112. {
  113. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name,
  114. Sha1Code = sha1
  115. };
  116. list.Add(model);
  117. }
  118. return list;
  119. }
  120. public async Task<AzureBlobModel> UploadPath(string path, string fileSpace = "common" , bool contentTypeDefault = false) {
  121. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  122. string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  123. blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  124. StorageUri url = blobContainer.StorageUri;
  125. FileInfo file = new FileInfo(path);
  126. string[] names = file.Name.Split(".");
  127. string name = "";
  128. for (int i = 0; i < names.Length - 1; i++)
  129. {
  130. name = name + names[i];
  131. }
  132. if (names.Length <= 1)
  133. {
  134. name = file.Name + "_" + newFileName;
  135. }
  136. else
  137. {
  138. name = name + "_" + newFileName + "." + names[names.Length - 1];
  139. }
  140. string fileext = file.Name.Substring(file.Name.LastIndexOf(".") > 0 ? file.Name.LastIndexOf(".") : 0);
  141. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  142. var blockBlob = blobContainer.GetBlockBlobReference(name);
  143. string content_type = "application/octet-stream";
  144. if (!contentTypeDefault)
  145. {
  146. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  147. if (!string.IsNullOrEmpty(contenttype))
  148. {
  149. blockBlob.Properties.ContentType = contenttype;
  150. content_type = contenttype;
  151. }
  152. else
  153. {
  154. blockBlob.Properties.ContentType = content_type;
  155. }
  156. }
  157. else
  158. {
  159. blockBlob.Properties.ContentType = content_type;
  160. }
  161. await blockBlob.UploadFromFileAsync(path);
  162. //var provider = new FileExtensionContentTypeProvider();
  163. //var memi = provider.Mappings[fileext];
  164. AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name , content_type)
  165. {
  166. Sha1Code=ShaHashHelper.GetSHA1(file.Create()),
  167. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  168. };
  169. return model;
  170. }
  171. public async Task<AzureBlobModel> UploadText(string fileName, string text, string fileSpace = "common", bool contentTypeDefault = true)
  172. {
  173. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  174. string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  175. blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  176. StorageUri url = blobContainer.StorageUri;
  177. //FileInfo file = new FileInfo(path);
  178. string[] names = fileName.Split(".");
  179. string name = "";
  180. for (int i = 0; i < names.Length - 1; i++)
  181. {
  182. name = name + names[i];
  183. }
  184. if (names.Length <= 1)
  185. {
  186. name = fileName + "_" + newFileName;
  187. }
  188. else
  189. {
  190. name = name + "_" + newFileName + "." + names[names.Length - 1];
  191. }
  192. var blockBlob = blobContainer.GetBlockBlobReference(name);
  193. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  194. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  195. string content_type = "application/octet-stream";
  196. if (!contentTypeDefault)
  197. {
  198. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  199. if (!string.IsNullOrEmpty(contenttype))
  200. {
  201. blockBlob.Properties.ContentType = contenttype;
  202. content_type = contenttype;
  203. }
  204. else
  205. {
  206. blockBlob.Properties.ContentType = content_type;
  207. }
  208. }
  209. else
  210. {
  211. blockBlob.Properties.ContentType = content_type;
  212. }
  213. await blockBlob.UploadTextAsync(text);
  214. byte[] bytes = System.Text.Encoding.Default.GetBytes(text);
  215. //var provider = new FileExtensionContentTypeProvider();
  216. //var memi = provider.Mappings[fileext];
  217. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, name, content_type, bytes.Length)
  218. {
  219. Sha1Code = ShaHashHelper.GetSHA1(bytes),
  220. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  221. };
  222. return model;
  223. }
  224. public async Task<AzureBlobModel> UploadObject(string fileName,object obj, string fileSpace = "common", bool contentTypeDefault =true)
  225. {
  226. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  227. string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  228. blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  229. StorageUri url = blobContainer.StorageUri;
  230. //FileInfo file = new FileInfo(path);
  231. string[] names = fileName.Split(".");
  232. string name = "";
  233. for (int i = 0; i < names.Length - 1; i++)
  234. {
  235. name = name + names[i];
  236. }
  237. if (names.Length <= 1)
  238. {
  239. name = fileName + "_" + newFileName;
  240. }
  241. else
  242. {
  243. name = name + "_" + newFileName + "." + names[names.Length - 1];
  244. }
  245. var blockBlob = blobContainer.GetBlockBlobReference(name);
  246. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  247. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  248. string content_type = "application/octet-stream";
  249. if (!contentTypeDefault)
  250. {
  251. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  252. if (!string.IsNullOrEmpty(contenttype))
  253. {
  254. blockBlob.Properties.ContentType = contenttype;
  255. content_type = contenttype;
  256. }
  257. else
  258. {
  259. blockBlob.Properties.ContentType = content_type;
  260. }
  261. }
  262. else {
  263. blockBlob.Properties.ContentType = content_type;
  264. }
  265. string objStr = obj.ToJsonAbs();
  266. await blockBlob.UploadTextAsync(objStr);
  267. //var provider = new FileExtensionContentTypeProvider();
  268. //var memi = provider.Mappings[fileext];
  269. byte[] bytes = System.Text.Encoding.Default.GetBytes(objStr);
  270. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, name, content_type , bytes.Length)
  271. {
  272. Sha1Code = ShaHashHelper.GetSHA1(bytes),
  273. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  274. };
  275. return model;
  276. }
  277. public async Task<AzureBlobModel> UploadFile(IFormFile file, string fileSpace = "wordfiles", bool contentTypeDefault = true)
  278. {
  279. long bizno= IdWorker.getInstance().NextId();
  280. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd")+"/"+ bizno;
  281. string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
  282. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  283. blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  284. StorageUri url = blobContainer.StorageUri;
  285. string[] names = file.FileName.Split(".");
  286. string name = "";
  287. for (int i = 0; i < names.Length - 1; i++)
  288. {
  289. name = name + names[i];
  290. }
  291. if (names.Length <= 1)
  292. {
  293. name = name + "_" + newFileName;
  294. }
  295. else
  296. {
  297. name = name + "_" + newFileName + "." + names[names.Length - 1];
  298. }
  299. var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
  300. var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  301. var blockBlob = blobContainer.GetBlockBlobReference(name);
  302. string fileext = filename.Substring(filename.LastIndexOf(".") > 0 ? filename.LastIndexOf(".") : 0);
  303. if (!contentTypeDefault)
  304. {
  305. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  306. if (!string.IsNullOrEmpty(content_type))
  307. {
  308. blockBlob.Properties.ContentType = content_type;
  309. }
  310. }
  311. await blockBlob.UploadFromStreamAsync(file.OpenReadStream());
  312. string sha1 = ShaHashHelper.GetSHA1(file.OpenReadStream());
  313. AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name)
  314. {
  315. Sha1Code=sha1,
  316. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  317. };
  318. return model;
  319. }
  320. public AzureBlobModel UploadFileByFolderNAsyn(Stream fileSteam, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  321. {
  322. string groupName = fileSpace + "/" + folder;
  323. // string newFileName = sha1Code;
  324. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  325. blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  326. StorageUri url = blobContainer.StorageUri;
  327. string[] names = fileName.Split(".");
  328. // string name ;
  329. //for (int i = 0; i < names.Length - 1; i++)
  330. //{
  331. // name = name + names[i];
  332. //}
  333. //if (names.Length <= 1)
  334. //{
  335. // name = newFileName;
  336. //}
  337. //else
  338. //{
  339. // name = newFileName + "." + names[names.Length - 1];
  340. //}
  341. //var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
  342. //var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  343. var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  344. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  345. if (!contentTypeDefault)
  346. {
  347. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  348. if (!string.IsNullOrEmpty(content_type))
  349. {
  350. blockBlob.Properties.ContentType = content_type;
  351. }
  352. else
  353. {
  354. blockBlob.Properties.ContentType = "application/octet-stream";
  355. }
  356. }
  357. blockBlob.UploadFromStreamAsync(fileSteam).GetAwaiter().GetResult() ;
  358. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, fileSteam.Length)
  359. {
  360. Sha1Code = ShaHashHelper.GetSHA1(fileSteam),
  361. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  362. };
  363. return model;
  364. }
  365. public async Task<AzureBlobModel> UploadFileByFolder(Stream fileSteam, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  366. {
  367. string groupName = fileSpace + "/" + folder;
  368. // string newFileName = sha1Code;
  369. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  370. blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  371. StorageUri url = blobContainer.StorageUri;
  372. string[] names = fileName.Split(".");
  373. // string name ;
  374. //for (int i = 0; i < names.Length - 1; i++)
  375. //{
  376. // name = name + names[i];
  377. //}
  378. //if (names.Length <= 1)
  379. //{
  380. // name = newFileName;
  381. //}
  382. //else
  383. //{
  384. // name = newFileName + "." + names[names.Length - 1];
  385. //}
  386. //var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
  387. //var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  388. var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  389. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  390. if (!contentTypeDefault)
  391. {
  392. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  393. if (!string.IsNullOrEmpty(content_type))
  394. {
  395. blockBlob.Properties.ContentType = content_type;
  396. }
  397. else {
  398. blockBlob.Properties.ContentType = "application/octet-stream";
  399. }
  400. }
  401. await blockBlob.UploadFromStreamAsync(fileSteam);
  402. string sha1 = ShaHashHelper.GetSHA1(fileSteam);
  403. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, fileSteam.Length)
  404. {
  405. Sha1Code = sha1,
  406. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  407. };
  408. return model;
  409. }
  410. public async Task<AzureBlobModel> UploadTextByFolder(string text, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  411. {
  412. string groupName = fileSpace + "/" + folder;
  413. blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  414. StorageUri url = blobContainer.StorageUri;
  415. var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  416. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  417. string content_type = "application/octet-stream";
  418. if (!contentTypeDefault)
  419. {
  420. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  421. if (!string.IsNullOrEmpty(contenttype))
  422. {
  423. blockBlob.Properties.ContentType = contenttype;
  424. content_type = contenttype;
  425. }
  426. else
  427. {
  428. blockBlob.Properties.ContentType = content_type;
  429. }
  430. }
  431. else
  432. {
  433. blockBlob.Properties.ContentType = content_type;
  434. }
  435. await blockBlob.UploadTextAsync(text);
  436. byte[] bytes = System.Text.Encoding.Default.GetBytes(text);
  437. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, bytes.Length)
  438. {
  439. Sha1Code = ShaHashHelper.GetSHA1(bytes),
  440. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  441. };
  442. return model;
  443. }
  444. /// <summary>
  445. /// 在容器上创建共享访问策略。
  446. /// </summary>
  447. /// <param name="container">A reference to the container.</param>
  448. /// <param name="policyName">The name of the stored access policy.</param>
  449. public async Task<bool> CreateSharedAccessPolicyAsync(string policyName,
  450. string containerName = null)
  451. {
  452. blobContainer = GetSASBoloClent(_options.Container);
  453. //Create a new shared access policy and define its constraints.
  454. SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
  455. {
  456. SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15),
  457. Permissions = SharedAccessBlobPermissions.Delete
  458. };
  459. //Get the container's existing permissions.
  460. BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  461. if (permissions.SharedAccessPolicies.Count < 5)
  462. {
  463. //Add the new policy to the container's permissions, and set the container's permissions.
  464. permissions.SharedAccessPolicies.TryAdd(policyName, sharedPolicy);
  465. await blobContainer.SetPermissionsAsync(permissions);
  466. return true;
  467. }
  468. else return false;
  469. }
  470. /// <summary>
  471. /// 删除容器上共享访问策略。
  472. /// </summary>
  473. /// <param name="container">A reference to the container.</param>
  474. /// <param name="policyName">The name of the stored access policy.</param>
  475. public async Task DeleteSharedAccessPolicyAsync(string policyName,
  476. string containerName = null)
  477. {
  478. blobContainer = GetSASBoloClent(_options.Container);
  479. BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  480. permissions.SharedAccessPolicies.Remove(policyName);
  481. await blobContainer.SetPermissionsAsync(permissions);
  482. }
  483. /// <summary>
  484. ///为 blob 容器创建服务 SAS
  485. /// 若要为容器创建服务 SAS,请调用 CloudBlobContainer.GetSharedAccessSignature 方法。
  486. ///下面的代码示例在容器上创建 SAS。 如果提供现有存储访问策略的名称,则该策略与 SAS 关联。 如果未提供存储访问策略,则代码会在容器上创建一个临时 SAS。
  487. /// </summary>
  488. /// <param name="container"></param>
  489. /// <param name="storedPolicyName"></param>
  490. /// <returns></returns>
  491. public (string, string) GetContainerSasUri(string containerName = null, string storedPolicyName = null)
  492. {
  493. string sasContainerToken;
  494. blobContainer = GetSASBoloClent(_options.Container);
  495. // If no stored policy is specified, create a new access policy and define its constraints.
  496. if (storedPolicyName == null)
  497. {
  498. // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  499. // to construct a shared access policy that is saved to the container's shared access policies.
  500. SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
  501. {
  502. // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
  503. // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  504. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  505. SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
  506. Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create| SharedAccessBlobPermissions.Read
  507. };
  508. // Generate the shared access signature on the container, setting the constraints directly on the signature.
  509. sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
  510. }
  511. else
  512. {
  513. // Generate the shared access signature on the container. In this case, all of the constraints for the
  514. // shared access signature are specified on the stored access policy, which is provided by name.
  515. // It is also possible to specify some constraints on an ad hoc SAS and others on the stored access policy.
  516. sasContainerToken = blobContainer.GetSharedAccessSignature(null, storedPolicyName);
  517. }
  518. // Return the URI string for the container, including the SAS token.
  519. return (blobContainer.Uri.ToString() , sasContainerToken);
  520. }
  521. public (string, string) GetContainerSasUriRead(string containerName, string storedPolicyName = null)
  522. {
  523. string sasContainerToken;
  524. blobContainer = GetSASBoloClent(containerName);
  525. // If no stored policy is specified, create a new access policy and define its constraints.
  526. if (storedPolicyName == null)
  527. {
  528. // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  529. // to construct a shared access policy that is saved to the container's shared access policies.
  530. SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
  531. {
  532. // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
  533. // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  534. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  535. SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
  536. Permissions = SharedAccessBlobPermissions.Read
  537. };
  538. // Generate the shared access signature on the container, setting the constraints directly on the signature.
  539. sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
  540. }
  541. else
  542. {
  543. // Generate the shared access signature on the container. In this case, all of the constraints for the
  544. // shared access signature are specified on the stored access policy, which is provided by name.
  545. // It is also possible to specify some constraints on an ad hoc SAS and others on the stored access policy.
  546. sasContainerToken = blobContainer.GetSharedAccessSignature(null, storedPolicyName);
  547. }
  548. // Return the URI string for the container, including the SAS token.
  549. return (blobContainer.Uri.ToString(), sasContainerToken);
  550. }
  551. /// <summary>
  552. /// 若要为 blob 创建服务 SAS,请调用 CloudBlob.GetSharedAccessSignature 方法。
  553. ///下面的代码示例在 blob 上创建 SAS。 如果提供现有存储访问策略的名称,则该策略与 SAS 关联。 如果未提供存储访问策略,则代码会在 Blob 上创建一个临时 SAS。
  554. /// </summary>
  555. /// <param name="container"></param>
  556. /// <param name="blobName"></param>
  557. /// <param name="policyName"></param>
  558. /// <returns></returns>
  559. public string GetBlobSasUri(string blobName, string containerName=null, string policyName = null)
  560. {
  561. string sasBlobToken;
  562. blobContainer = GetSASBoloClent(_options.Container);
  563. // Get a reference to a blob within the container.
  564. // Note that the blob may not exist yet, but a SAS can still be created for it.
  565. CloudBlockBlob blob = blobContainer.GetBlockBlobReference( blobName );
  566. if (policyName == null)
  567. {
  568. // Create a new access policy and define its constraints.
  569. // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  570. // to construct a shared access policy that is saved to the container's shared access policies.
  571. SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
  572. {
  573. // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
  574. // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  575. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  576. SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
  577. Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read
  578. };
  579. // Generate the shared access signature on the blob, setting the constraints directly on the signature.
  580. sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
  581. }
  582. else
  583. {
  584. // Generate the shared access signature on the blob. In this case, all of the constraints for the
  585. // shared access signature are specified on the container's stored access policy.
  586. sasBlobToken = blob.GetSharedAccessSignature(null, policyName);
  587. }
  588. // Return the URI string for the container, including the SAS token.
  589. return blob.Uri + sasBlobToken;
  590. }
  591. public string GetBlobSasUriRead(string containerName, string blobName, string policyName = null)
  592. {
  593. string sasBlobToken;
  594. blobContainer = GetSASBoloClent(containerName);
  595. CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName);
  596. if (policyName == null)
  597. {
  598. SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
  599. {
  600. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  601. SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
  602. Permissions = SharedAccessBlobPermissions.Read
  603. };
  604. sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
  605. }
  606. else
  607. {
  608. sasBlobToken = blob.GetSharedAccessSignature(null, policyName);
  609. }
  610. return blob.Uri + sasBlobToken;
  611. }
  612. private CloudBlobContainer GetSASBoloClent(string containerName)
  613. {
  614. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_options.ConnectionString);
  615. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
  616. CloudBlobContainer container = blobClient.GetContainerReference(containerName);
  617. return container;
  618. }
  619. public async Task Deleteblob(string azureBlobSAS)
  620. {
  621. (string, string) a = BlobUrlString(azureBlobSAS);
  622. string ContainerName = a.Item1;
  623. string BlobName = a.Item2;
  624. string PolicyName = "DeletePolicy";
  625. bool flg = await CreateSharedAccessPolicyAsync(PolicyName);
  626. if (flg)
  627. {
  628. string SAS = GetBlobSasUri(BlobName, null, PolicyName);
  629. CloudBlockBlob blob = new CloudBlockBlob(new Uri(SAS));
  630. await blob.DeleteAsync();
  631. }
  632. await DeleteSharedAccessPolicyAsync(PolicyName);
  633. }
  634. private static (string, string) BlobUrlString(string sasUrl)
  635. {
  636. sasUrl = sasUrl.Substring(8);
  637. string[] sasUrls = sasUrl.Split("/");
  638. string ContainerName;
  639. ContainerName = sasUrls[1].Clone().ToString();
  640. string item = sasUrls[0] + "/" + sasUrls[1] + "/";
  641. string blob = sasUrl.Replace(item, "");
  642. return (ContainerName, blob);
  643. }
  644. }
  645. }