0

I am defining my application URLs like

domainname.com/storecontroller/storeaction/storename

I want to rewrite like

domainname.com/storecontroller/storename

Actually, I need to skip storeaction from the url, I don't want to do it with querystring with "?" Is there anyway to do it by registering rout config path or any another way?

Nomi Ali
  • 2,165
  • 3
  • 27
  • 48

2 Answers2

1

Yes. You can define action as a default parameter, and match for only specific controllers with a Regex constraint:

routes.MapRoute("<route name>", "{controller}/{storename}", 
     new 
     { 
         action = "storeaction" 
     },
     new
     {
         controller = "somecontroller1|somecontroller2|somecontroller3",
     });

(Action will always have the default value "storeaction")

Note that you need to define this route before the default generic route so it doesn't catch it before this kicks in.

Kapol
  • 6,383
  • 3
  • 21
  • 46
Sedat Kapanoglu
  • 46,641
  • 25
  • 114
  • 148
  • You answer is perfect however for each controller do I need to register another route. how about if I need to have 10 to 20 controllers. – Nomi Ali Aug 08 '16 at 21:05
  • 1
    @NomiAli you can use Regex constraints to limit matches to certain controllers, see my edited answer. – Sedat Kapanoglu Aug 08 '16 at 21:10
1

Using Attribute routing

[RoutePrefix("Home")]
public ActionResult HomeController : Controller
{
  [Route("{storeName}")]
  public ActionResult ProcessStore(string storeName)
  {
   // to do : Return something
  }

  public ActionResult Index()
  {
   // to do : Return something
  }
}
[RoutePrefix("Payment")]
public ActionResult PaymentController : Controller
{
  [Route("{storeName}")]
  public ActionResult ProcessStore(string storeName)
  {
   // to do : Return something
  }
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • In 1st) if my URL is like "anothercontroller/anotheraction" in that case its surely doesn't work as It should catch at that "anotheraction" method exist in my "anothercontroller." In 2nd) it's doesn't work may be it need something in routeconfig? – Nomi Ali Aug 08 '16 at 21:33
  • @NomiAli True. I removed that part. Sedat's answer will address that. Attribute routing version of my answer will still work. – Shyju Aug 08 '16 at 22:00