[英]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.