我得到了与MongoDB一起工作的最小API,我需要将所有请求方法放入"PersonController"控制器中

app.MapGet("/api/users", () =>
    db.GetCollection<Person>(collectionName).Find("{}").ToListAsync());
 
app.MapGet("/api/users/{id}", async (string id) =>
{
    var user = await db.GetCollection<Person>(collectionName)
        .Find(p=>p.Id == id)
        .FirstOrDefaultAsync();
 
    if (user == null) return Results.NotFound(new { message = "User is not found" });
 
    return Results.Json(user);
});
app.MapDelete("/api/users/{id}", async (string id) =>
{
    var user = await db.GetCollection<Person>(collectionName).FindOneAndDeleteAsync(p=>p.Id==id);
    // if not found send status code and error message
    if (user is null) return Results.NotFound(new { message = "User is not found" });
    return Results.Json(user);
});

app.MapPost("/api/users", async (Person user) => {
 
    // adding user to the list
    await db.GetCollection<Person>(collectionName).InsertOneAsync(user);
    return user;
});
 
app.MapPut("/api/users", async (Person userData) => {
 
    var user = await db.GetCollection<Person>(collectionName)
        .FindOneAndReplaceAsync(p => p.Id == userData.Id, userData, new() { ReturnDocument = ReturnDocument.After });
    if (user == null) 
        return Results.NotFound(new { message = "User is not found" });
    return Results.Json(user);
});

我是.NET新手,我不知道如何将这些请求放入控制器中.

推荐答案

我有与MongoDB一起工作的最小API,我需要将所有请求 方法添加到"PersonController"控制器中.我是.NET新手,我 不知道如何将这些请求放入控制器.

实际上,在.NET应用程序中创建API控制器非常简单,无论其版本如何.我不确定您使用的是哪个版本的.NET,但我将与您分享如何在.NET7中实现您的要求.

通过两种方式,您可以包括现有的最低API操作,或者创建新的API项目,或者在现有项目中创建新的API控制器.

在现有项目中创建新的API控制器:

  1. 使用控制器创建新的文件夹名称:

enter image description here

您应该具有以下文件夹和名称:

enter image description here

  1. 使用Person创建新的Web API控制器名称,并按以下方式替换您的代码:

enter image description here

enter image description here

    [Route("api/[controller]")]
    [ApiController]
    public class PersonController : ControllerBase
    {

        private readonly PersonService _personService;

        public PersonController(PersonService personService) =>
            _personService = personService;

        [HttpGet]
        public async Task<List<Person>> Get() =>
            await _personService.Find();

        [HttpGet("{id:length(24)}")]
        public async Task<ActionResult<Person>> Get(string id)
        {
            var person = await _personService.Find(id);

            if (person is null)
            {
                return NotFound();
            }

            return person;
        }

        [HttpPost]
        public async Task<IActionResult> Post(Person newPerson)
        {
            await _personService.InsertOneAsync(newPerson);

            return CreatedAtAction(nameof(Get), new { id = newPerson.Id }, newPerson);
        }

        [HttpPut("{id:length(24)}")]
        public async Task<IActionResult> Update(string id, Person updatedPerson)
        {
            var person = await _personService.Find(id);

            if (person is null)
            {
                return NotFound();
            }

            updatedPerson.Id = person.Id;

            await _personService.ReplaceOneAsync(id, updatedPerson);

            return NoContent();
        }

        [HttpDelete("{id:length(24)}")]
        public async Task<IActionResult> Delete(string id)
        {
            var person = await _personService.Find(id);

            if (person is null)
            {
                return NotFound();
            }

            await _personService.DeleteOneAsync(id);

            return NoContent();
        }


    }

演示模型:

public class Person
    {
       public string Id { get; set; }   
       public string Name { get; set; }   
    }

Mongo集合配置:

public class PersonDatabaseSettings
    {
        public string ConnectionString { get; set; } = null!;

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

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

数据库收集服务:

public class PersonService
    {
        private readonly IMongoCollection<Person> _personCollection;

        public PersonService(
            IOptions<PersonDatabaseSettings> personDatabaseSettings)
        {
            var mongoClient = new MongoClient(
                personDatabaseSettings.Value.ConnectionString);

            var mongoDatabase = mongoClient.GetDatabase(
                personDatabaseSettings.Value.DatabaseName);

            _personCollection = mongoDatabase.GetCollection<Person>(
                personDatabaseSettings.Value.GetCollection);
        }

        public async Task<List<Person>> Find() =>
            await _personCollection.Find(_ => true).ToListAsync();

        public async Task<Person?> Find(string id) =>
            await _personCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

        public async Task InsertOneAsync(Person newPerson) =>
            await _personCollection.InsertOneAsync(newPerson);

        public async Task ReplaceOneAsync(string id, Person updatedPerson) =>
            await _personCollection.ReplaceOneAsync(x => x.Id == id, updatedPerson);

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

Note:我正在使用额外的服务等级,但您可以继续,您的方法也是如此.

Program.cs:

由于您已经使用了最低版本的API,因此在使用API控制器时,您应该按如下方式更新您的Program.cs文件:

using APIProject.Controllers;

var builder = WebApplication.CreateBuilder(args);


builder.Services.Configure<PersonDatabaseSettings>(
    builder.Configuration.GetSection("PersonDatabase"));

// Add services to the container.

builder.Services.AddSingleton<PersonService>();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Note: WEN应在Program.cs中注册Mongo DB客户端和PersonService DI,同上.

输出:

我还没有在我的VM中安装mongo db实例,因此收集将 引发空引用异常,但如果存在 数据收集.

enter image description here

Note:以获取任何实施挑战或进一步信息please refer to this official document.

Csharp相关问答推荐

如何打印已添加到List的Linq值,而不是C#中的:System.Collections.Generic.List ' 1[System.Int32]?

无法将blob发送到Azure -缺少HTTP标头异常

无法使用ternal- .net修复可空警告

在Dapper中使用IasyncEum重写GetAsyncEum方法

一小时后,自定义缓存停止在App Insight中保存

. NET在上一个操作完成之前,在此上下文实例上启动了第二个操作

如何在不考虑年份的情况下判断日期时间是否在某个日期范围内?

从依赖项容器在.NET 8中的Program.cs文件中添加IOC

如何通过寻找向量长度来优化两个循环?

C#中浮点数的System.Text.Json序列化问题

在两个已具有一对多关系的表之间添加另一个一对多关系

在C#中,是否有与变量DISARD对应的C++类似功能?

使用CollectionView时在.NET Maui中显示数据时出现问题

.Net MAUI,在将FlyoutPage添加到容器之前,必须设置添加构造函数导致Flyout和Detail"

解决方案:延长ABP框架和ANGING OpenIddict中的令牌生命周期

如何使用EPPlus C#在单个单元格中可视化显示多行文字

类/值和日期的泛型方法

使用C#12中的主构造函数进行空判断

C#;AvaloniaUI;MVVM;当另一个窗口上的按钮被单击时,如何更新视图图像源?

C#-如何将int引用获取到byte[]