【问题标题】:Url route with id without controller带有 id 的 URL 路由,没有控制器
【发布时间】: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" });

标签: c# asp.net asp.net-mvc model-view-controller


【解决方案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();
    }
    ...
}

【讨论】:

    猜你喜欢
    • 2013-02-02
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多