views:

1561

answers:

4

Hi there

I would like to create a url just like followings :

http://localhost/news/announcement/index http://localhost/news/health/index http://localhost/news/policy/index

announcement, health, policy are controller

so I make a new url route map like this :

routes.MapRoute( "News", "news/{controller}/{action}/{id}", new { controller = "Announcement", action = "Index", id = "" } );

It works fine but, following two urls show same page :

http://localhost/news/announcement/index http://localhost/announcement/index

I would like to prevent second url.

What shoud I do?

Thanks Kwon

+7  A: 

If you have still have the default route set up, you'll need to remove it or add a route constraint so that it doesn't match your news path.

Remove this:

routes.MapRoute( "Default",
                 "{controller}/{action}/{id}",
                 new { controller = "Home", action = "Index", id = "" } );

Or add a constraint:

routes.MapRoute( "Default",
                 "{controller}/{action}/{id}",
                 new { controller = "Home", action = "Index", id = "" },
                 new { controller = "(Home|Other)" } );

The constraint will allow the default route to match only controllers Home and Other, but not Announcment, Health, or Policy (or anything else for that matter).

tvanfosson
So what's happening is the first URL is matching on your custom route but the second URL is matching on the default route.
Graphain
Is "other" reserved keyword in mvc framework?
@Graphain -- that's my suspicion, but it's hard to know without seeing the entire code.
tvanfosson
@kwon -- 'Other' was just an example of another controller since I don't know what your controllers are named. If you have no other controllers than the ones in "news", then you really don't need the "default" route at all.
tvanfosson
+1  A: 

If there is any default route mapping then move it to the end of your mappings. If that doesn't help then you can try Url Routing Debugger.

idursun
A: 

Logically speaking second url should not work. Because news is your application name which is hosted in IIS and i guess you might have put that in Default website. So if you are accessing the application URL will be always

http://localhost/news/controller/action

and if you give this

http://localhost/controller/action, it doesnt know which application to look.

i suggest you to create a virtual directory 'news' if you have not created one and then publish everything there. Also make sure you have not published your application files in Inetpub\wwwroot\ directory.

Am waiting for your reply to continue.

Say
A: 

I mean "sub folder", not "application" or "virtual directory" I think tvanfosson's answer, especially by constraint is enough for my question. But, I am still wondering that what "new { controller = "(Home|Other)" " means. I am sorry I am a just new commer in asp.net mvc.