How to hide controller name in Url?

How to hide controller name in Url?

I use the ASP.NET MVC.

The original url is: http://www.sample.com/Users.mvc/UserDetail/9615

The “Users” is controller name, the “UserDetail” is action name, and the “9615” is UserId.

How can I hide the controller name and action name in the url.

Just like this: http://www.sample.com/9615

I have writed the following code in the Global.ascx.cs to hide the action name:

routes.MapRoute(
             "UserDetail",             // Route name
             "Users.mvc/{UserId}",              // URL with parameters
             new { controller = "Users", action = "UserDetail", UserId = "" }  // Parameter defaults
            );

Using the above code I hid the action name and got this url: http://www.sample.com/Users.mvc/9615

But how can I hide the controller name and get this url: http://www.sample.com/9615

Thanks.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The idea is the same. You do just the thing you did to the action. However, your problem arises from the fact that IIS is probably not mapping www.xyz.com/1234 to ASP.NET runtime. To do so in IIS7, enable integrated mode and in IIS6, add a wildcard mapping in handler map that maps everything to ASP.NET.

To add a wildcard map, see http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx (Search for “IIS6 Extension-less URLs” in that page)

After that, simply add a route:

routes.MapRoute("UserDetails", "{UserID}/{*name}", 
    new { controller = "Users", action = "UserDetail" , UserID=""});

This should do the trick.

Method 2

MVC recognizes the difference between “{UserID}” and “{id}” so if you are going to have a route with only “{UserID}” in the Url you need to place it first in the list other wise it never gets hit. And make sure the default includes “id” since it will continually loop over “UserDetails” unless the default references id as apposed to UserID. I found this format works for me:

routes.MapRoute("UserDetails",
       "{UserID}",
       new { controller = "Users", action = "UserDetail", id = "" }
);
routes.MapRoute(
       "Default", // Route name
       "{controller}/{action}/{id}", // URL with parameters               
       new { controller = "Account", action = "LogOn", id = "" } // Parameter defaults   
);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x