繁体   English   中英

默认控制器操作在 .NET 6 MVC 中如何工作?

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

查看 .NET 6 中的项目模板之一,我可以看到:

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

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

Get方法可以通过调用/weatherforecast来调用,但我不明白为什么。 /weatherforecast/get不应该是正确的网址吗? 默认的控制器操作方法应该是Index 为什么它有效?

您说的是 ApiController,这意味着它是通过 http 请求创建的。

[HttpGet]属性指定您希望通过 HTTP GET 公开此方法。

如果您执行[HttpGet("my-method")]行,则端点将是/api/<controllername>/my-method

所以如果你想要 url 是/weatherforecast/get你必须将它指定为

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

微软网站上有很好的解释

如下更改第 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.

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