将所有 URL 路由到家庭控制器操作 C# MVC

Route all URL's to Home controller action C# MVC

我想在 C# 中创建一个 URL 重定向器,所以每当我的 MVC 应用程序基础 url 被参数击中时,我想将它重定向到其他 url 基于url 中的参数(站点、文件夹、文件、ID 等) 例如:http://localhost:8080/site/folder/file/id 或 http://localhost:8080/site/folder/file 或 http://localhost:8080/site/folder 等。 所以requesturl可以是任何类型,只有baseurl会被固定。

我尝试将默认路由更新为

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

我还尝试创建一条自定义新路线作为

routes.MapRoute(
    "DCTM",                                             // Route name
    "Da/{objectId}",                                    // URL with parameters
    new { controller = "Home", action = "Redirector" }  // Parameter defaults
);

但是以上两种方法都报错。可以做些什么来实现这一目标?

我找到解决办法了!!! 将网络应用程序的任何传入 url 重定向到任何其他网络应用程序,如下所示

  • 将 RouteConfig.cs 更新为
 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

            routes.MapRoute(
                 name: "Dctm",
                 url: "{*nodeAliasPath}",
                 defaults: new { controller = "Home", action = "Redirector", id = UrlParameter.Optional }
             );
        }
  • 现在添加目标 url 并将源的 url 添加到 HomeController.cs 中作为
 public ActionResult Redirector()
        {
            string destinationURL = "Destination base url" + Request.RawUrl; // combine the destination base url and source url parameters. 
            return Redirect(destinationURL);
        }

输出:

  • 来源URL:https://localhost:44306/Abc/Xyz/632-sn232-erh4
  • 重定向 URL: https://localhost:44396/Abc/Xyz/632-sn232-erh4