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:
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
?
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']);
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.
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With