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?

3
  • You want this for all the controllers or a specific controller ? Commented Aug 8, 2016 at 20:57
  • i want to do it for 2 or 3 controllers only. Commented Aug 8, 2016 at 20:58
  • [RoutePrefix("/storecontroller/{storename}")] you should be able to add a route prefix for specific controllers Commented Aug 8, 2016 at 21:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@NomiAli you can use Regex constraints to limit matches to certain controllers, see my edited answer.
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
  }
}

2 Comments

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?
@NomiAli True. I removed that part. Sedat's answer will address that. Attribute routing version of my answer will still work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.