简体   繁体   中英

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

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?

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

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()
    {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM