Reputation: 13
I am using MongoDB to setup and host my database for my project, I've been following the official Microsoft doc on how to set up a Web API for MongoDB. I've done everything just as the doc had but routing isn't working. When I try http://localhost:55536/api/user It returns a 404 error.
The controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using StudyAPI.Models;
using StudyAPI.Services;
namespace StudyAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly UserService _userService;
public UserController(UserService userService)
{
_userService = userService;
}
[HttpGet]
public ActionResult<List<User>> Get() =>
_userService.Get();
[HttpGet("{id:length(24)}", Name = "GetUser")]
public ActionResult<User> Get(string id)
{
var user = _userService.Get(id);
if (user == null)
{
return NotFound();
}
return user;
}
[HttpPost]
public ActionResult<User> Create(User user)
{
_userService.Create(user);
return CreatedAtRoute("GetUser", new { id = user.Id.ToString() }, user);
}
[HttpPut("{id:length(24)}")]
public IActionResult Update(string id, User userIn)
{
var user = _userService.Get(id);
if (user == null)
{
return NotFound();
}
_userService.Update(id, userIn);
return NoContent();
}
[HttpDelete("{id:length(24)}")]
public IActionResult Delete(string id)
{
var user = _userService.Get(id);
if (user == null)
{
return NotFound();
}
_userService.Remove(user.Id);
return NoContent();
}
}
}
CRUD Operations Service
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StudyAPI.Models;
namespace StudyAPI.Services
{
public class UserService
{
private readonly IMongoCollection<User> _users;
public UserService(IStudyDBSettings settings)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_users = database.GetCollection<User>(settings.UserCollection);
}
public List<User> Get() =>
_users.Find(user => true).ToList();
public User Get(string id) =>
_users.Find<User>(user => user.Id == id).FirstOrDefault();
public User Create(User user)
{
_users.InsertOne(user);
return user;
}
public void Update(string id, User userIn) =>
_users.ReplaceOne(user => user.Id == id, userIn);
public void Remove(User userIn) =>
_users.DeleteOne(user => user.Id == userIn.Id);
public void Remove(string id) =>
_users.DeleteOne(user => user.Id == id);
}
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using StudyAPI.Models;
using StudyAPI.Services;
namespace StudyAPI
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<StudyDBSettings>(
Configuration.GetSection(nameof(StudyDBSettings)));
services.AddSingleton<IStudyDBSettings>(sp =>
sp.GetRequiredService<IOptions<StudyDBSettings>>().Value);
services.AddSingleton<UserService>();
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
}
Running IIS Express works and displays "Hello World!" but aside from that, routing to /api/etc doesn't work.
Upvotes: 1
Views: 600
Reputation: 4913
You should add endpoints.MapControllers();
to the Startup
file.
Change the app.UseEndpoints
to :
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
endpoints.MapControllers();
});
I hope you find this helpful.
Upvotes: 2