开发者

How do I set up RESTFul URLs using ASP.NET MVC routing?

开发者 https://www.devze.com 2023-02-15 07:28 出处:网络
I have this URL: /controller/action/value and this action: public ActionResult Get(string configName,string addParams)

I have this URL:

/controller/action/value

and this action:

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

How do I set up my 开发者_C百科routing table to get the routing engine bind the value to the configName parameter for any action in the Config controller?


Well, first off, that is incomplete. You don't have a method name.

Secondly, this will already work with URLs of the format:

/controller/action?configName=foo&addparams=bar

Here's how to do it with pretty routes:

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

or

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

if you want to exclude the action from the URL.


You could add a new route above the default

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
);

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


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

Setting default Controller to Home, with a Default Action of Index

So the Url: /config/get/configNameValue/AddParamValue

would match this Method:

public ActionResult Get(string configName,string addParams)
{
//Do Stuff 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号