0

I am new to C# MVC, This is my default RouteConfig File,

public class RouteConfig
{
    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 }
        );
    }
}

When I run my project http://localhost:50382 it redirects the default home index method.

How can I build custom url like http://localhost:50382/somestringcode and call a specific ActionMethod. Something Like a custom route that points to specific ActionMethod and the stringcode will be passed as parameter.

public ActionResult Method1( string code)
{
    return View();
}
Presto
  • 888
  • 12
  • 30
Anuj Tamrakar
  • 251
  • 2
  • 13

2 Answers2

1

What you are searching for is attribute routing. That means specifying URL routes explicitly.
First, you need to enable it

routes.MapMvcAttributeRoutes();

Then add Route attribute to desired action:

[Route("")]
public ActionResult Method1( string code)
 {
     return View();
 }

Since code parameter is simple type, it will be searched in request URL.

Tomas Chabada
  • 2,869
  • 1
  • 17
  • 18
0

You need to do something like this, where controller1 is the controller name that contains Method1, and make sure you place this first, and leave the original route config, so when it doesn't match this route, it will use default route. Please note this is bad practice, and it will fail in case route is trying to access default action for a controller "Index" as @stephen mentioned in the comments below, and that's why I would suggest adding a prefix ex "Action1" to the route.

routes.MapRoute
(
    name: "Method1",
    url: "Action1/{code}",
    defaults: new { controller = "controller1", action = "Method1", code = "default"}
);
Presto
  • 888
  • 12
  • 30
Munzer
  • 2,216
  • 2
  • 18
  • 25
  • Thank you , you solved my problem :) – Anuj Tamrakar Jul 06 '18 at 06:08
  • 1
    Wrong - all the other routes would fail. If a user enters `../Home` or `../Products` or anthing with one segment, if would that method instead of the intended `Index` method of those controllers –  Jul 06 '18 at 06:14
  • Thanks a lot @StephenMuecke , I am not sure how I missed this, usually I would suggest appending something to the route, something like `"Method1/{code}"` but I follow his preference, and it is very bad practice, and it will fail as you mentioned. – Munzer Jul 06 '18 at 06:18
  • 1
    Adding a prefix would be fine, otherwise you need a route constraint as per the duplicate –  Jul 06 '18 at 06:20