get Bson byte[] from c# List<MongoDBModel> models and save in asp.net core web app session
时间: 2024-03-02 13:52:11 浏览: 91
Sure, here's an example code snippet to get a Bson byte array from a C# `List<MongoDBModel>` and save it in ASP.NET Core web app session:
```csharp
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
// Assuming MongoDBModel class exists
List<MongoDBModel> models = new List<MongoDBModel>();
// Assuming "HttpContext" is the current HttpContext object
// Serialize the models list to a BsonArray
BsonArray bsonArray = new BsonArray();
foreach (var model in models)
{
bsonArray.Add(BsonDocument.Parse(model.ToJson()));
}
// Convert the BsonArray to a byte array
byte[] bsonBytes = bsonArray.ToBson();
// Save the byte array in session
HttpContext.Session.Set("MongoDBModels", bsonBytes);
```
Here, we first convert the `List<MongoDBModel>` to a `BsonArray` and then serialize it to a byte array using the `ToBson()` method. Finally, we save the byte array in the session using the `Set()` method of the `HttpContext.Session` object.
阅读全文