[英]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:查看 .NET 6 中的项目模板之一,我可以看到:
[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. Get
方法可以通过调用/weatherforecast
来调用,但我不明白为什么。 Shouldn't /weatherforecast/get
be the correct url? /weatherforecast/get
不应该是正确的网址吗? The default controller action method should be Index
.默认的控制器操作方法应该是
Index
。 Why does it work?为什么它有效?
Because you added [HttpGet]
attribute to the method.因为您在方法中添加了
[HttpGet]
属性。
https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0#verb6 https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0#verb6
you're talking about an ApiController, which means it is created to be consumed via an http request.您说的是 ApiController,这意味着它是通过 http 请求创建的。
The [HttpGet]
attribute specifies that you want to expose this method via HTTP GET. [HttpGet]
属性指定您希望通过 HTTP GET 公开此方法。
if you do something line [HttpGet("my-method")]
the endpoint would be /api/<controllername>/my-method
如果您执行
[HttpGet("my-method")]
行,则端点将是/api/<controllername>/my-method
so if you want the url the be /weatherforecast/get
you have to specify it as所以如果你想要 url 是
/weatherforecast/get
你必须将它指定为
[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如下更改第 2 行以获得您想要的
[ApiController]
//Change this line
//[Route("[controller]")]
//Like
[Route("[controller]/[action]")]
public class WeatherForecastController : ControllerBase
{
// ...
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.