c# - Azure Blob 存储保存 Dto

标签 c# .net azure azure-blob-storage

我想将一些对象 (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.

输出:-

enter image description here

enter image description here

关于c# - Azure Blob 存储保存 Dto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76071035/

相关文章:

c# - 如何获取作为函数传递的匿名方法的参数值?

c# - 删除 FileSystemWatcher 正在监视的文件夹

c# - 更简单的写 null 或 empty 的方法?

c# - 如何确定 Azure ServiceBus PrefetchCount 和 ReceiveBatch 大小

c# - 了解 Google V8 的架构

c# - 如何让语言永久改变?

c# - '反序列化操作的回复消息正文时出错......' - 对于我调用的每个方法

c# - 重置网络连接

c# - 如何根据范围查询结果删除Azure表实体

asp.net-mvc - 在 MVC API 中使用 Microsoft Azure Active Directory 验证 OAuth 2.0 不记名 token 时出现 401