Home > Net >  How do I register wep api controller in .net core 6?
How do I register wep api controller in .net core 6?

Time:02-18

I have created a small app in .net core 6.

Here is the project structure.

project
│   
└───wwwroot
│   │   Content 
└───Api
    │   ResturantsController
    │   

Now I have ResturantsController

here is the class.

namespace OdeToFood.Api
{
    [Route("api/RestaurantsController")]
    [ApiController]
    public class RestaurantsController : ControllerBase
    {

        [Route("api/Restaurants")]
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
}

in my program.cs

I have the following:

using OdeToFood.Data;
using Microsoft.EntityFrameworkCore;
// required for command line to tell ef that my startp project is here;
using Microsoft.EntityFrameworkCore.Design;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddScoped<IRestaurantData,SqlRestaurantData>();
// EF
builder.Services.AddDbContextPool<OdeToFoodDbContext>(Options =>
 {
     Options.UseSqlServer(builder.Configuration.GetConnectionString("OdeToFoodDb"));
 });
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
// Api controllers
app.MapControllers();
app.MapDefaultControllerRoute();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

I am trying to access the api using the following end point https://localhost:7285/api/Restaurants

I am getting the 404.

Any reason ?

CodePudding user response:

add in startup

builder.Services.AddControllers();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers(); // Map attribute-routed API controllers
    endpoints.MapRazorPages();//map razor pages
});

and rename Api folder to Controllers.

CodePudding user response:

Seems you are using [Route] attribute twice on your controller I have noticed. First one at the top of your global RestaurantsController and another is on the top of your action that's why you are getting your [Route] as /api​/Restaurants​/api​/Restaurants

Solution:

Simple solution is remove [Route("...")] attribute either from global controller or from action like below:

Keep Route in global controller:

    [Route("api/[controller]")]
    [ApiController]
    public class RestaurantsController : ControllerBase
    {
       
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "Restaurent value1", "Restaurent value2" };
        }
    }

Keep Route in controller action:

[ApiController]
public class RestaurantsController : ControllerBase
{
    [Route("api/Restaurants")]
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "Restaurent value1", "Restaurent value2" };
    }
}

Note: Both would produce the [Route] as https://localhost:7285/api/Restaurants

Output:

enter image description here

That would work as per your expectations without any further modifications on Program.cs file. And above steps are simplest one with minimal changes.

  • Related