简体   繁体   English

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

[英]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?为什么它有效?

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.

相关问题 默认帐户控制器在服务器ASP.NET MVC 5上不起作用 - Default Account Controller does not work on server ASP.NET MVC 5 asp.net mvc如何将视图与控制器动作联系起来? - how does asp.net mvc relate a view to a controller action? 在asp.net mvc中设置索引操作默认操作控制器 - set index action default action controller in asp.net mvc MVC路由不适用于虚拟目录上的非默认/根操作控制器 - MVC routing does not work for non-default/root action controller on virtual directory ASP.NET MVC 5身份验证:默认代码如何工作? - ASP.NET MVC 5 authentication: how does default code work? ASP.NET MVC缺少默认操作仅适用于一个控制器 - ASP.NET MVC Missing Default Action only for one controller Asp.Net MVC 中 Web API 的默认控制器操作 - Default controller action for Web API in Asp.Net MVC 在ASP.NET MVC 3中为控制器设置默认操作(而不是索引) - Set default action (instead of index) for controller in ASP.NET MVC 3 如何在asp.net MVC4中将默认值为False的复选框传递给控制器​​操作 - How to Pass default values as False of checkBox to controller action in asp.net mvc4 如何让ASP.NET MVC为区域设置默认的Controller和Action? - How do I get ASP.NET MVC to set a default Controller and Action for an Area?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM