Search code examples
restasp.net-coreasp.net-core-mvchttp-status-code-404

Error 404 when starting the server on ASP.NET Core MVC


I need to write a server for a veterinary clinic management system. From the web application, doctors will be able to log into their personal accounts and view their work schedule.

I wrote the code for models, views and controllers, but it tells me that the error is 404 (HTTP ERROR 404). There is probably an error in routing, but if you write /api or /doctor/login in the URL, it won't do any good.

Also, when creating the project, I did not have a startup file, I created it manually, maybe this is the problem.

This is my doctor controller:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
using VetCareServ.Data;
using VetCareServ.DTO;
using VetCareServ.Models;

[Route("api/[controller]")]
[ApiController]
public class DoctorsController : ControllerBase
{
    private readonly VetCareServDbContext _context;

    public DoctorsController(VetCareServDbContext context)
    {
        _context = context;
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] DoctorLoginModel doctorLogin)
    {
        if (ModelState.IsValid)
        {
            var authenticatedDoctor = await _context.DoctorLoginModel
                .FirstOrDefaultAsync(d => d.DoctorEmail == doctorLogin.DoctorEmail && d.DoctorPassHash == doctorLogin.DoctorPassHash);

            if (authenticatedDoctor != null)
            {
                var doctorInfo = await _context.Doctors
                    .FirstOrDefaultAsync(d => d.DoctorEmail == doctorLogin.DoctorEmail);

                return RedirectToAction("Account", new { id = doctorInfo.DoctorId });
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Неверные учетные данные");
                return BadRequest(ModelState);
            }
        }

        return BadRequest(ModelState);
    }

    [HttpGet("account/{id}")]
    public async Task<IActionResult> Account(int id)
    {
        var doctor = await _context.Doctors.FindAsync(id);

        if (doctor == null)
        {
            return NotFound();
        }

        return Ok(doctor);
    }
}

And this is startup.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using VetCareServ.Data;

namespace VetCareServ
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<VetCareServDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddControllersWithViews();
            services.AddSession();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseSession();
       
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Doctor}/{action=Login}/{id?}");//it seems to be right!
            });

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            
            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

If my approach is initially wrong, I would be grateful to hear how to do it better! This is my first time writing a server using this technology, so I'm not sure how good it is. I'm trying to learn how to do servers using ASP.NET Core MVC model with REST (to send data by JSON files).


Solution

  • Pls allow me to have a summary here.

    I did not have a startup file

    Starting from .net 6, we don't have the Startup.cs file by default, all codes write in Startup before are put in Program.cs

    And you mentioned that you are having an MVC project, so you should have below default routing template, but this would also be covered by your routing attribute.

    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    

    Just like what mar_c said in the comment, the route for your controller should be Post /api/doctors/login and Get /api/doctors/account/{id}. For the 415 error, Content-Type application/json in request header is required.

    enter image description here enter image description here enter image description here