Pankaj
Pankaj

Reputation: 10095

Url without controllerName

I want to hide the controller name from URL. I am using the below code.

routes.MapRoute(
    name: "Customized",
    url: "{action}",
    defaults: new { controller = "Home", action = "Default", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Default", id = UrlParameter.Optional }
);

This works perfecly.

but only works when i type

http :// domain/ActionName

otherwise, I still able to see

http :// domainname/controller/action

Is there any way to http ://domain/ActionName even if user tried to type

http :// domainname/controller/action

Upvotes: 3

Views: 1725

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239210

You could potentially do something hacky like check the actual path once you got into the action and if it's not the right path, then redirect to the right path, but that technically causes two requests and could hammer your server if done frequently enough.

MVC Routing employs short-circuit logic to match the request path with an appropriate action. It doesn't care that there may be a "better" route that the user should have used, it only cares that it found a match.

Upvotes: 0

jbl
jbl

Reputation: 15413

If you have only one Controller (Home) I guess you can have only one route definition ( assuming all your actions share the same parameter pattern) :

routes.MapRoute(
    name: "Customized",
    url: "{action}/{id}",
    defaults: new { controller = "Home", action = "Default", id = UrlParameter.Optional }
);

Upvotes: 2

Related Questions