我想将一些对象 (DTO) 直接保存到 Azure Blob 存储。我找到了使用 BinaryFormatter 的解决方案,但根据本文 ( https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide ),不建议这样做。
所以,我想我会将数据转换为 JSON 并对其进行压缩。还有另一种方法可以将对象直接保存到 blob 中吗?
谢谢
最佳答案
通过序列化和压缩 DTO 对象,您可以压缩生成的 JSON 数据。使用像下面的代码一样的compressedStream来异步上传blob。
代码:-
using System.Text.Json; using Azure.Storage.Blobs; namespace MyNamespace { public class MyDto { public int Num { get; set; } public string Place { get; set; } public DateTime Startedat { get; set; } } class Program { static async Task Main(string[] args) { //Create a MyDto object using this code. var myObject = new MyDto { Num = 3, Place = "dto", Startedat = DateTime.UtcNow }; // Convert the object to JSON. var options = new JsonSerializerOptions { WriteIndented = true }; var json = JsonSerializer.Serialize(myObject, options); // Compress JSON using var compressedStream = new MemoryStream(); using var gzipStream = new GZipStream(compressedStream, CompressionMode.Compress); using var writer = new StreamWriter(gzipStream); writer.Write(json); writer.Flush(); var connectionString = "DefaultEndpointsProtocol=https;AccountName=storageaccountname;AccountKey=xxxxxxxxxxxtu7OGErfF4WsrLocnQOsxAqVg0azDou1vEATj8osRx+3o+ASt1/hvig==;EndpointSuffix=core.windows.net"; var containerName = "siliconcon"; var blobName = "siliconvalley"; var blobServiceClient = new BlobServiceClient(connectionString); var containerClient = blobServiceClient.GetBlobContainerClient(containerName); var blobClient = containerClient.GetBlobClient(blobName); compressedStream.Seek(0, SeekOrigin.Begin); await blobClient.UploadAsync(compressedStream); Console.WriteLine("Object uploaded successfully!"); } } } ```
I have used this link to initiate JsonSerializerOptions class in this line :- var options = new JsonSerializerOptions { WriteIndented = true }; in the above code and also referred these MS document. samples.
输出:-
关于c# - Azure Blob 存储保存 Dto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76071035/