【问题标题】:Remove controller name from URL with Attribute routing使用属性路由从 URL 中删除控制器名称
【发布时间】:2016-02-18 05:16:54
【问题描述】:

我想从特定控制器的 URL 中删除控制器名称。

我的控制器名称是Product

我找到了一些链接来做这个

Routing with and without controller name

MVC Routing without controller

但上述所有链接都在路由配置文件中完成。这些也影响其他控制器。我想使用属性路由来做到这一点。

这可能吗?因为我只想为产品控制器执行此操作。

我尝试过这样的操作

[Route("Sample/{Name}")]

但它不起作用。

【问题讨论】:

    标签: c# asp.net asp.net-mvc routing


    【解决方案1】:

    Gabriel 的回答是正确的,但是,它可能会有点误导,因为您要求的是 MVC,而该答案是针对 Web API。

    无论如何,您想要的是将注释放在类定义而不是操作方法上。 MVC 示例如下:

    [RoutePrefix("SomethingOtherThanProduct")]
    public class ProductController : Controller
    {
          public ActionResult Index()
          {
               ...
               return View();
          }
    }
    

    我也放弃了这个作为答案,因为您可能会发现以下文章有帮助:[Attribute] Routing in ASP.NET MVC 5 / WebAPI 2

    【讨论】:

      【解决方案2】:

      确保在整个控制器类上设置 RoutePrefix 属性,并在操作上使用 Route 属性。

      [RoutePrefix("notproducts")]
      public class ProductsController : ApiController
      {
          [Route("")]
          public IEnumerable<Product> Get() { ... }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-05
        • 1970-01-01
        • 2011-09-16
        • 1970-01-01
        • 2018-01-10
        • 2013-08-15
        • 1970-01-01
        相关资源
        最近更新 更多