ASP.NET6 + Mongo + OData

时间:2023-02-12 07:08:29

准备工作

  • Docker环境
  • Mongo数据库
  • 配置Mongo数据库

ASP.NET6 集成Mongo

安装MongoDB.Driver
ASP.NET6 + Mongo + OData

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
            }
    },
    "BookStoreDatabase": {
        "ConnectionString": "mongodb://localhost",
        "DatabaseName": "BookStore",
        "BooksCollectionName": "Books"
        },
    "AllowedHosts": "*"
}
public class BookStoreDatabaseSettings
{
    public string ConnectionString { get; set; } = null!;

    public string DatabaseName { get; set; } = null!;

    public string BooksCollectionName { get; set; } = null!;
}
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace MongoExample.Models;

public class Book
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string? Id { get; set; }

    [BsonElement("Name")]
    public string BookName { get; set; } = null!; 
    
    public decimal Price { get; set; }

    public string Category { get; set; } = null!;

    public string Author { get; set; } = null!;
}
using MongoDB.Driver;
using MongoExample.Models;
using Microsoft.Extensions.Options;

namespace MongoExample.Services;

public class BookService
{
    private readonly IMongoCollection<Book> _bookCollection;

    public BookService(IOptions<BookStoreDatabaseSettings> bookStoreDatabaseSettings)
    {
        var mongoClient = new MongoClient("mongodb://admin:000000@localhost:27017");
        var mongoDatabase = mongoClient.GetDatabase(bookStoreDatabaseSettings.Value.DatabaseName);
        _bookCollection = mongoDatabase.GetCollection<Book>(bookStoreDatabaseSettings.Value.BooksCollectionName);
    }

    public async Task<List<Book>> GetBooksAsync() => await _bookCollection.Find(_ => true).ToListAsync();

    public async Task<Book> GetBookAsync(string id) => await _bookCollection.Find(x=>x.Id == id).FirstOrDefaultAsync();

    public async Task CreateAsync(Book book) => await _bookCollection.InsertOneAsync(book);

    public async Task UpdateAsync(string id, Book updatedBook) => await _bookCollection.ReplaceOneAsync(x=>x.Id == id, updatedBook);

    public async Task RemoveAsync(string id) => await _bookCollection.DeleteOneAsync(x=>x.Id ==id); 
}

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using MongoExample.Models;
using MongoExample.Services;

namespace MongoExample.Controllers;

[ApiController]
[Route("/api/[controller]")]
public class BooksController : ControllerBase
{
    private readonly BookService _bookService;

    public BooksController(BookService bookService)
    {
        this._bookService = bookService;
    }

    [HttpGet]
    [EnableQuery]
    public async Task<List<Book>> Get() => await _bookService.GetBooksAsync();

    [HttpGet("{id:length(24)}")]
    public async Task<ActionResult<Book>> GetBook(string id)
    {
        var book = await _bookService.GetBookAsync(id);
        if (book == null)
        {
            return NotFound();
        }

        return book;
    }

    [HttpPost]
    public async Task<ActionResult> Create(Book book)
    {
        await _bookService.CreateAsync(book);
        return CreatedAtAction("Get", new { id = book.Id }, book);
    }

    [HttpPut("{id:length(24)}")]
    public async Task<IActionResult> Update(string id, Book updatedBook)
    {
        var book = await _bookService.GetBookAsync(id);
        if (book == null)
        {
            return NotFound();
        }

        updatedBook.Id = book.Id;
        await _bookService.UpdateAsync(id, updatedBook);
        return NoContent();
    }

    [HttpDelete("{id:length(24)}")]
    public async Task<IActionResult> Delete(string id)
    {
        var book = await _bookService.GetBookAsync(id);
        if (book == null)
        {
            return NotFound();
        }

        await _bookService.RemoveAsync(id);
        return NoContent();
    }
}

ASP.NET6 集成OData

VS22022基于.NET6基础上创建的asp.net core web api模板已经合并了Startup和Program类, 所有的服务注入,中间件注入都合并在了Program类中, 好久没写C#了,这个类这次变化有点大。
安装OData
ASP.NET6 + Mongo + OData
合并后的模板只有Program.cs类,没有了Startup类,也就是之前的服务注入都是通过ConfigServices方法,IServiceCollection实现。 如果不习惯的话也可以自己手动创建一个Startup类,然后在Program类中调用该类。

using Microsoft.AspNetCore.OData;
using MongoExample.Models;
using MongoExample.Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.Configure<BookStoreDatabaseSettings>(builder.Configuration.GetSection("BookStoreDatabase"));
builder.Services.AddSingleton<BookService>();
//这里注入OData查询方法
builder.Services.AddControllers().AddOData(options => options.Select().Filter().OrderBy());

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

测试OData Query

查询Category和BookName字段
http://localhost:5220/api/books?$select=Category,BookName
响应JSON值

[{"Category":"Computer","BookName":"Design Patters"},{"Category":"Software","BookName":"Java In Action"},{"Category":"Software","BookName":"C# In Action"}]

查询Category和BookName字段并且用Category倒叙排列

[{"Category":"Software","BookName":"Java In Action"},{"Category":"Software","BookName":"C# In Action"},{"Category":"Computer","BookName":"Design Patters"}]