0

My Environment Windows 10. Visual Studio 2019 Professional, Asp.Net Core 3.1

I am following a Pluralsight course to teach myself Asp.Net Core 3.1. Following the instructor, I have created the web application. Everything goes well until the instructor adds an api controller to the application. It works for him but not for me.

Here's my api controller

namespace OdeToFood.Api
{
    [Route("api/[controller]")]
    [ApiController]
    public class RestaurantsController : ControllerBase
    {
        private readonly OdeToFoodDbContext _context;

        public RestaurantsController(OdeToFoodDbContext context)
        {
            _context = context;
        }

        // GET: api/Restaurants
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Restaurant>>> GetRestaurants()
        {
            return await _context.Restaurants.ToListAsync();
        }

        // GET: api/Restaurants/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Restaurant>> GetRestaurant(int id)
        {
            var restaurant = await _context.Restaurants.FindAsync(id);

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

            return restaurant;
        }

. . . . .

Here's my project structure and hierarchy. enter image description here

When I rebuild my project, and call the app from local IIS Express, i.e. https://localhost:44351/ It loads fine. I can interact fully, browse and CRUD entities. However when I point to any api url, e.g. https://localhost:44351/api/Restaurants or https://localhost:44351/api/Restaurants/2 I get "This localhost page can’t be found". The api simply does not load or respond in any way.

I am familiar with MVC5 where, when creating a new project, in the create project wizard scaffolding, you could check a box to add api functionality. I am not seeing this in VS2019 for Asp.Net Core 3.1 We Apps.

I promise you have have done my homework before asking this question here. I have googled to death. I have seen MS articles on core 3.1 breaking changes. I have looked at online project templates. I have searched stackoverflow. Maybe my search terms are flawed and I'm simply missing something simple.

Questions:

  1. Why is the api shown above not loading?

  2. Is there a way to add api functionality to an existing Asp.Net Core 3.1 Web Application or do I need to create a separate api project?

  3. Is there a way to create a new Asp.Net Core 3.1 Web Application with api functionality included?

My thanks in advance

Kieran

1
  • Just Give a simple try with string return from method,and check if it works or not. I just copied your code and tested with String return it is working fine for me. Commented Sep 3, 2020 at 11:05

1 Answer 1

2

If you'd like to add web APIs feature into an existing Razor Pages project, you need to do additional configuration, like below.

public void ConfigureServices(IServiceCollection services)
{
    //add services for controllers
    services.AddControllers();

    services.AddRazorPages();

    //...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //...

    app.UseRouting();

    //...

    app.UseEndpoints(endpoints =>
    {
        //add endpoints for controller actions
        endpoints.MapControllers();

        endpoints.MapRazorPages();
    });
}

Testing code of controller and action(s)

[Route("api/[controller]")]
[ApiController]
public class RestaurantsController : ControllerBase
{
    public IActionResult GetRestaurants()
    {
        return Ok("Restaurants List Here");
    }
}

Test Result

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

None of the above works. Is there a way for me to post my Startup.cs without clicking "answer your own question" ? It includes everything you mention. Note, the api controller is never hit. A breakpoint in the constructor is never called.
I've just discovered that I needed to add a 'endpoints.MapControllers();' line to the app.UseEndpoints(endpoints => lambda. Now it works. So in Startup.cs, under Configure, use app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); });
needed to add a 'endpoints.MapControllers();' line to the app.UseEndpoints(endpoints => lambda. Now it works Hi @user2026382, if you check my above sample code carefully, you would find that I have pointed that with a comment '//add endpoints for controller actions' in example. If the solution did help resolve the problem, you can refer to this link to accept it as answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.