MongoDB Web API 快速入门指南
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ExampleMongoDBWebAPI.Controllers
{
public class UsersController : Controller
{
private readonly IMongoCollection<User> _users;
public UsersController(IMongoCollection<User> users)
{
_users = users;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetAll()
{
return await _users.Find(new BsonDocument()).ToListAsync();
}
[HttpGet("{id:length(24)}")]
public async Task<ActionResult<User>> GetById(string id)
{
var user = await _users.Find(u => u.Id == id).FirstOrDefaultAsync;
if (user == null)
{
return NotFound();
}
return user;
}
[HttpPost]
public async Task<ActionResult<User>> Create(User user)
{
user.Id = ObjectId.GenerateNewId().ToString();
await _users.InsertOneAsync(user);
return CreatedAtRoute(nameof(GetById), new { id = user.Id }, user);
}
[HttpDelete("{id:length(24)}")]
public async Task<IActionResult> Delete(string id)
{
var deleteResult = await _users.DeleteOneAsync(u => u.Id == id);
if (deleteResult.DeletedCount == 0)
{
return NotFound();
}
return NoContent();
}
}
public class User
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}
这个代码示例展示了如何使用ASP.NET Core MVC创建一个简单的MongoDB Web API控制器。它包括了基本的CRUD操作,并使用了MongoDB的官方驱动程序来与数据库交互。这个示例对于学习如何将MongoDB集成到Web API应用程序中是非常有用的。
评论已关闭