Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • http://localhost:8080/api/Users
  • http://localhost:8080/api/GetUsers
  • http://localhost:8080/Configuration/api/Users
  • http://localhost:8080/Configuration/api/GetUsers

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 ?

like image 857
Roman Pokrovskij Avatar asked Jan 26 '19 03:01

Roman Pokrovskij


People also ask

How do I add a controller to my route?

Basic Controllers You can define a route to this controller method like so: use App\Http\Controllers\UserController; Route::get('/user/{id}', [UserController::class, 'show']);

What is Areas folder in Web API?

NET Web API. Areas are used for the management of the project. They are used in large projects. We create more than one area in a project.

How do I create a route in API?

Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.

What is the base controller for all Web API controller to inherit from?

In ASP.NET MVC 5 and Web API 2, there were two different Controller base types. MVC controllers inherited from Controller ; Web API controllers inherited from ApiController .


1 Answers

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

like image 157
Laksmono Avatar answered Nov 11 '22 16:11

Laksmono