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

I want to create a URL re-director in c#, so whenever my MVC application base url is hit with parameters i want to redirect it to other url based on parameters in the url (site, folder, file, id, etc)
Eg: http://localhost:8080/site/folder/file/id or http://localhost:8080/site/folder/file or http://localhost:8080/site/folder etc.
So request url can be of any type, only base url will be fixed.

I tried to update the default route as

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

Also i tried to create a custom new route as

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

But both the above approaches are giving error. What can be done to achieve this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I have got the solution!!!
Redirect any incoming url of a web app to any other web app as below

  • Update the RouteConfig.cs as

 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 }
             );
        }
  • Now add the destination url and append the url of source to it in HomeController.cs as

 public ActionResult Redirector()
        {
            string destinationURL = "Destination base url" + Request.RawUrl; // combine the destination base url and source url parameters. 
            return Redirect(destinationURL);
        }

Output:
  • Source URL: https://localhost:44306/Abc/Xyz/632-sn232-erh4
  • Redirect URL: https://localhost:44396/Abc/Xyz/632-sn232-erh4


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x