Sunday, July 18, 2010

ASP.net MVC Routing - Part1


In ASP.net MVC Routing works following way and need to register in Application_Start of Global.asax

Default Route when ASP.net MVC Application created

routes.MapRoute(
   "Default", // Route name
   "{controller}/{action}/{id}", // URL with parameters
   new { controller = "Default", action = "Index", id = UrlParameter.Optional });

Default route has placeholder that done most of work.

For example :

if request is made for http://<<yoursite>//Home/Index.
This will call HomeController’s Index method.

if request is made for http://<<yousite>//Home/Index/1
This will call HomeController’s Index method with argument value “1”.

Sample Controller:
public class HomeController : Controller
    {      
        public ActionResult Index(string id)
        {
            return new ContentResult() { Content = "This is Index" };
        }
    }

Next Part will going to give you detail about “Slugish Url”.

ASP.net 4.0 Url Routing


In ASP.net 4.0 , New functionality included for URL Routing.

For Example : ( Application_Start)
RouteTable.Routes.MapPageRoute("Default","Home","~/Default.aspx");

When Browser request for http://<<your site>>/Home, It will route to page Default.aspx

And Page has some property that allow you to get route data, Page.RouteData

Even generic route is also possible.

RouteTable.Routes.MapPageRoute("Default","{Home}","~/{Home}.aspx");

Now When request made for Url : http://<<yoursite>/Test It automatically route to Test.aspx

One more thing true about ASP.net 4.0 routing is even though routing is done, there is still possible that direct request for “ASPX” pages.

To disable that

1. from UI (IIS 7.0 or later)
       - Go to inetmgr
       - In Feature View go to “Request Filtering”
         image  
       - Click Deny FileName Extension 
        image

2.  Using main web.config file of your application          
 <system.webServer>
     <modules runAllManagedModulesForAllRequests="true" />
        <security>
            <requestFiltering>
                <fileExtensions>
                    <add fileExtension=".aspx" allowed="false" />
                </fileExtensions>
            </requestFiltering>
        </security>
  </system.webServer>
    - Add Module tag with runAllManagedModulesForAllRequests = “true”
    - Add requestfiltering with fileextension=”.aspx” and “allowed=false”.


Let me know your comment on this.