带有 id 的 URL 路由,没有控制器

Posted

技术标签:

【中文标题】带有 id 的 URL 路由,没有控制器【英文标题】:Url route with id without controller 【发布时间】:2021-06-02 03:47:09 【问题描述】:

我有一个问题,我想设置一个这样的 url 路由https://www.niris.si/1234 -> 这是 id 代替 https://www.niris.si/ControllerName/ActionName/1234

这可能吗?

我试过下面的代码

 endpoints.MapControllerRoute(
                name: "Name",
                pattern: "/id?",
                defaults: new  Controller="RandomController", action = "Index" );

但我只能让它像这样工作: https://www.niris.si/ControllerName/1234

使用这段代码:

endpoints.MapControllerRoute(
                name: "Name",
                pattern: "RandomController/id?",
                defaults: new  Controller="RandomController", action = "Index" );

在这种情况下,我删除了动作名称,但没有删除控制器名称。

感谢您的帮助和建议,亲切的问候

【问题讨论】:

如果RandomController 是您的控制器类的名称,则需要在MapControllerRoute() 中将控制器名称定义为:defaults: new Controller="Random", action = "Index" ); 【参考方案1】:

尝试绘制如下路线:

// For ASP.NET Core 
endpoints.MapControllerRoute("Random", pattern: "id?", new  Controller = "Random", action = "Index" );

// For ASP.NET MVC
public class RouteConfig

    public static void RegisterRoutes(RouteCollection routes)
    
        routes.IgnoreRoute("resource.axd/*pathInfo");

        routes.MapRoute(
            name: "Default",
            url: "id",
            defaults: new  controller = "Random", action = "Index", id = UrlParameter.Optional 
        );
    

// ASP.NET Core MVC
public class RandomController : Controller
        
    public IActionResult Index(int? id)
    
        // TODO: Your the action code here ...

        return View();
    
    ...


// ASP.NET MVC
public class RandomController : Controller
        
    public ActionResult Index(int? id)
    
        // TODO: Your the action code here ...

        return View();
    
    ...

【讨论】:

以上是关于带有 id 的 URL 路由,没有控制器的主要内容,如果未能解决你的问题,请参考以下文章

带有 POST 请求的 Laravel 路由 URL 参数

SEO 友好 URL 的 URL 路由

一个带有两个控制器的路由

Zend Framework 2 中的路由,跳过 url 中的“索引”操作但获取 id

mvc——URL路由_1_定义路由(映射url到动作方法)

带有模型数据的 MVC 5 路由