How to configure a RESTFul URL using ASP.NET MVC routing?

I have this url:

/controller/action/value

and this action:

public ActionResult Get(string configName,string addParams)
{
}

How to configure the routing table to force the routing mechanism to bind a value to a parameter configNamefor any action in the controller Config?

+3
source share
3 answers
routes.MapRoute(
      "ValueMapping",                                            
      "config/{action}/{configName}/{addParams}",          
      new { controller = "Config", action = "Index", configName= UrlParameter.Optional, addParams = UrlParameter.Optional }  // Parameter defaults);

Setting the standard controller to the main one, with the default action for the index

So Url: /config/get/configNameValue/AddParamValue

will match this method:

public ActionResult Get(string configName,string addParams)
{
//Do Stuff 
}
+2
source

Well, firstly, it is incomplete. You do not have a method name.

Secondly, it will already work with format URLs:

/ controller / action configName = Foo &? Addparams = bar

Here's how to do it with good routes:

routes.MapRoute(
      "YourMapping",                                            
      "{controller}/{action}/{configName}/{addParams}");

or

routes.MapRoute(
      "YourMapping",                                            
      "{controller}/{configName}/{addParams}",     
      new {
          controller = "YourController",
          action = "YourAction"
      },
      new {
          controller = "YourController"  // Constraint
      });

URL.

+5

routes.MapRoute(
  "Config", 
  "config/{action}/{configName}/{addParams}",
  new { controller = "Config", action = "Index" }
);

routes.MapRoute(
  "Default", // Route name
  "{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

This will allow you to use the route /config/actionName/configName/addParamsValue. Your other routes should not be affected by this.

+3
source

All Articles