English 中文(简体)
CRUD业务没有在我的网页上工作,大概是蒙戈布问题
原标题:CRUD operations don t work in my web api, presumably mongodb problem

我有一只网皮和CRUD业务,尽管我有所有必要的控制人员。 我认为,它有“测试”数据库,“用户”收集。

页: 1 NET,因此,我犯了几吨错误,这是我的<编码>program.cs。 法典:

using metanit.Controllers;

var builder = WebApplication.CreateBuilder(args);


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

builder.Services.AddSingleton<PersonService>();

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();


app.UseDefaultFiles();
app.UseStaticFiles();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

并且是个人主计长:

using metanit.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MongoDB.Driver;

namespace metanit.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    
    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 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);
    }
}

以及

appsettings.json
{
  "PersonDatabase": {
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "test",
    "GetCollection": "users"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

我试图把我的照片连接到<代码>mongo db,但CRUD业务没有工作。 页: 1 NET,因此,也许我没有明显的东西。

问题回答

I have web api app and CRUD operations aren t performed, though I have all necessary controllers. I think it s mongodb related issue; I have "test" database with "users" collection.

诚然,从你们共同的法典来看,你无法把蒙戈大 instance与你一样。 我看到,在方案.cs中,你没有登记过重要服务,请参见我的方案科。

除此以外,确保您有,在https://www.mongodb.com/docs/manual/installation/“rel=”上安装了,并在

创建Mongo Db and Collection:

enter image description here

在表格中加入几个目标:

You can do as following

enter image description here enter image description here

<>说明: Mongo的情况是敏感的,所有财产名称都应较低,对这两者进行误导可能会造成500德里亚顿的错误,并意识到这一点。

套头:

Make sure, your appsetting for Mongo Db configuration are correct, you can refer to following:

"PersonDatabaseSettings": {
    "CollectionName": "Persons",
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "PersonDb"
  },

“entergraph

注:我的收集名称是个人,我的数据库Name是个人资料,它聆听了港口<条码>>mongodb http:// localhost:27017”。 我相信,你的配置是正确的。

Program.cs:

var builder = WebApplication.CreateBuilder(args);


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



// Add services to the container.

builder.Services.AddSingleton<IPersonDatabaseSettings>(sp =>
            sp.GetRequiredService<IOptions<PersonDatabaseSettings>>().Value);

builder.Services.AddSingleton<PersonService>();

builder.Services.AddControllers()
    .AddJsonOptions(
        options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

<>说明: 以上配置是为了管理抽样。

拆解模式:

 public class Person
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        [BsonElement("name")]
        public string Name { get; set; }
        [BsonElement("email")]
        public string Email { get; set; }
    }

Mondo Collection Configuation:

public class PersonDatabaseSettings : IPersonDatabaseSettings
    {
        public string CollectionName { get; set; }
        public string ConnectionString { get; set; }
        public string DatabaseName { get; set; }
    }

    public interface IPersonDatabaseSettings
    {
        public string CollectionName { get; set; }
        public string ConnectionString { get; set; }
        public string DatabaseName { get; set; }
    }

<>说明: • 确保你在节目中登记以上。

拥有Mongo客户的个人服务:

public class PersonService
    {
        private readonly IMongoCollection<Person> _personCollection;
        public PersonService(IPersonDatabaseSettings settings)
        {
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);

            _personCollection = database.GetCollection<Person>(settings.CollectionName);

        }
        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);
        

    }

主计长:

    [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()
        {
            return await _personService.Find();
        }

    }

产出:

Get Request: enter image description here

“enterography

员额请求:

“entergraph

<>说明: 你可以看到,我成功地从APIC获得数据,利用红戈收集并给它带来新的目标。 请





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签