安裝MongoDB.Driver
{
"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();
}
}
VS22022基於.NET6基礎上建立的asp.net core web api模板已經合併了Startup和Program類, 所有的服務注入,中介軟體注入都合併在了Program類中, 好久沒寫C#了,這個類這次變化有點大。
安裝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();
查詢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"}]
部落格地址: | http://www.cnblogs.com/sword-successful/ |
部落格版權: | 本文以學習、研究和分享為主,歡迎轉載,但必須在文章頁面明顯位置給出原文連線。 如果文中有不妥或者錯誤的地方還望高手的你指出,以免誤人子弟。如果覺得本文對你有所幫助不如【推薦】一下!如果你有更好的建議,不如留言一起討論,共同進步! 再次感謝您耐心的讀完本篇文章。 |