Search code examples
asp.net-coreasp.net-core-webapirazor-pagesasp.net-core-2.2

ASP Core: how to route to API Controller that is located in the area folder?


The structure:

+ MyProj
   + Areas
       + Configuration
          - Pages
          - ConfigurationApiController.cs

To create controller without Controllers folder was proposed by VS2017 and it is ok for me since I use Razor Pages and do not need Controllers folder:

enter image description here

Those doesn't work:

Controller defined:

[Route("api")]
[Produces("application/json")]
[ApiController]
public class ConfigurationApiController : ControllerBase
{
    private readonly ApplicationSettings applicationSettings;
    [HttpGet]
    public ActionResult GetUsers()
    {

Mvc routing configured standard way:

app.UseMvc(routes =>
            {

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

How to route to GetUsers action of ConfigurationApiController ?


Solution

  • Modify the api route and add the Area Attribute to provide the area name for [area] route.

        [Area("Configuration")]
        [Route("[area]/api/[controller]")]
        [ApiController]
        public class ConfigurationApiController : ControllerBase
        {
        }
    

    That's all, and it can be accessed at http://localhost:8080/Configuration/api/ConfigurationApi