Home > Blockchain >  How does the default controller action work in .NET 6 MVC?
How does the default controller action work in .NET 6 MVC?

Time:06-12

Looking at one of the project templates in .NET 6, I can see this:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    // ...

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {

The Get method can be invoked by calling /weatherforecast, but I don't understand why. Shouldn't /weatherforecast/get be the correct url? The default controller action method should be Index. Why does it work?

CodePudding user response:

Because you added [HttpGet] attribute to the method.

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0#verb6

CodePudding user response:

you're talking about an ApiController, which means it is created to be consumed via an http request.

The [HttpGet] attribute specifies that you want to expose this method via HTTP GET.

if you do something line [HttpGet("my-method")] the endpoint would be /api/<controllername>/my-method

so if you want the url the be /weatherforecast/get you have to specify it as

[HttpGet("get")]
public IEnumerable<WeatherForecast> Get()
{}

It is very well explained on the microsoft site

CodePudding user response:

Change the line no 2 as below to get what you want

[ApiController]
//Change this line 
//[Route("[controller]")]
//Like
[Route("[controller]/[action]")]
public class WeatherForecastController : ControllerBase
{
    // ...

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
  • Related