首页 > 编程语言 >ASP.NET6 + Mongo + OData

ASP.NET6 + Mongo + OData

时间:2023-02-11 22:55:23浏览次数:44  
标签:ASP string OData await id book using NET6 public

准备工作

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

ASP.NET6 集成Mongo

安装MongoDB.Driver
QQ截图20230211223816.png

{
    "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
QQ截图20230211223710.png
合并后的模板只有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"}]

标签:ASP,string,OData,await,id,book,using,NET6,public
From: https://www.cnblogs.com/sword-successful/p/17112750.html

相关文章

  • ASP.NET Core - 入口文件
    1.入口文件  一个应用程序总有一个入口文件,是应用启动代码开始执行的地方,这里往往也会涉及到应用的各种配置。当我们接触到一个新框架的时候,可以从入口文件入手,了解入......
  • ASP.NET Core 系列总结
    《ASP.NETCore》系列文章基于.NET3.1和.NET6,主要是系统总结自己日常工作和学习中的知识点,之前是自己在OneNote上自己写,作为学习、总结笔记,逐渐放出来也供大家参......
  • Asp.Net Core中利用过滤器控制Nginx的缓存时间
    前言Web项目中很多网页资源比如html、js、css通常会做服务器端的缓存,加快网页的加载速度一些周期性变化的API数据也可以做缓存,例如广告资源位数据,菜单数据,商品类目数据,商......
  • 【3】.NET6最通俗易懂的依赖注入之服务容器与作用域
    这篇文章是ASP.NET6依赖注入系列文章的第3篇。在上一篇文章中,我们讨论依赖注入的基本用法与生命周期。接下来,在这篇文章中,我们继续深入了解服务容器相关的概念。服......
  • Dockerize ASP Classic on IIS
    DockerizeASPClassiconIISAskQuestionAsked 4years,1monthagoActive 9monthsagoViewed 9ktimes 2216Microsofthasbeeninvesti......
  • Asp.net: sometimes OutOfMemoryException when many w3wp processes run
    Asp.net:sometimesOutOfMemoryExceptionwhenmanyw3wpprocessesrunAskQuestionAsked 4years,11monthsagoModified 4years,11monthsagoIhaveani......
  • Troubleshoot Out of Memory issues In ASP.Net
    Learn Troubleshoot WebApps ASP.NET TroubleshootOutofMemoryissues(System.OutOfMemoryException)inASP.NETArticle01/25/20227minutestorea......
  • ASP.NET Core+Element+SQL Server开发校园图书管理系统(完)
    随着技术的进步,跨平台开发已经成为了标配,在此大背景下,ASP.NETCore也应运而生。本文主要基于ASP.NETCore+Element+SqlServer开发一个校园图书管理系统为例,简述基于MVC三......
  • .Net6对AOP的多种支持之IAsyncResourceFilter
     环境:.Net6Web项目Mvc结构开发工具:VS2022IAsyncResourceFilter(资源缓存异步)IAsyncResourceFilter扩展   ASP.NETCore6提供的是接口IAsyncResourceFilter......
  • kettle 报错 org.owasp.encoder
    在生成xml时候需要对密码加密处理也可以注释StringtransXml=transMeta.getXML();maven<dependency><groupId>org.owasp.esapi</groupId>......