【问题标题】:.Net: Does controller have to have file name corresponding to URL?.Net:控制器是否必须具有与 URL 对应的文件名?
【发布时间】:2020-02-14 17:31:25
【问题描述】:

我在 .Net 控制器上关注 this tutorial,它显示“假设您在浏览器的地址栏中输入以下 URL:http://localhost/Product/Index/3。在这种情况下,调用了一个名为 ProductController 的控制器。”

我想知道的:

为了成功命中http://localhost/Product/Index/3,是否需要一个专门叫ProductController的控制器?

【问题讨论】:

标签: asp.net asp.net-mvc controller asp.net-controls


【解决方案1】:

不,没有必要。您可以使用路由属性。

[Route("new-name-for-product")]
public class ProductController{

}

现在您必须使用http://localhost/new-name-for-product/Index/ 这个 URL 来调用 ProductController。 如果你想对这个 URL 使用一个或多个参数,你必须为 ActionMethod 使用不同的路由模板。下面的例子。

[Route("new-name-for-product")]
public class ProductController
{

// http://localhost/new-name-for-product/3/ will show product details based on id
// http://localhost/new-name-for-product/Index/3/ will show product details based on id

[HttpGet]
[Route("/{id}")]
public IActionResult Index(int id)
{
// your code
}

// you can use a different action method name. 
// http://localhost/details/3/ will show product details based on id
// but parameter name (Ex: id) and the id inside route template the spelling must be the same.

[HttpGet]
[Route("details/{id}")]
public IActionResult GetById(int id)
{
// your code
}
}

【讨论】:

    【解决方案2】:

    这取决于。在 ASP.Net Core 中,路由可以配置为常规路由或属性路由。

    常规路由配置如下:

    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); 
    

    这里,第一个路径段映射到控制器名称, 第二个映射到动作名称, 第三段用于映射到模型实体的可选 id。

    按照惯例,控制器文件名通常与控制器类名相同。 因此,在常规路由中,url 将与文件名匹配。

    URL http://localhost/Products/Index 与 ProductsController 中的以下操作方法匹配。

    [Route("[controller]")]
    public class ProductsController : Controller
    {
       [HttpPost("Index")]     // Matches 'Products/Index'  
       public IActionResult Index()
        {
            return View();
        }
    }
    

    属性路由

    使用属性路由,控制器名称和动作名称在选择动作时不起任何作用。 因此,它与文件名无关。

    URL http://localhost/Items/All 与 ProductsController 中的以下操作方法匹配。

    public class ProductsController : Controller
    {
       [Route("Items/All")]
       public IActionResult Index()
       {
          return View();
       }
    }
    

    同样,[Route] 属性可以在 Controller 和 action 方法中添加。相同的 URL http://localhost/Items/All 匹配如下所示的操作方法:

    [Route("Items")]
    public class ProductsController : Controller
        {
           [Route("All")]
           public IActionResult Index()
           {
              return View();
           }
        }
    

    有关更多详细信息,您可以参考微软文档https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 2015-05-04
      • 2015-03-27
      • 2021-06-27
      • 2014-10-19
      相关资源
      最近更新 更多