Saturday, 14 February 2015

Understanding Application Routes In MVC–This is what Microsoft says



Understanding Application Routes –This is what Microsoft says

In my previous post I mentioned the URL is resolved via URL routing module in ASP.Net MVC. I also specifically said that request must match predefined URL pattern e.g. Customers/Add can be one such pattern which means I want to add a customer or Customer/Show/Id=1 can be another such pattern which means I want to show the details of the customer whose customer id is 1. Thus we are moving away from our old way of depending upon files and tightly coupled code behind it. Examine carefully don’t you think it’s like acting on resources which compelled you to go in REST (Representational State Transfer) direction. So just hold your breath although ASP.Net MVC allows you to use a pure REST approach ASP.Net MVC is loosely REST oriented. Loosely REST oriented means it does acknowledge concepts such as resource and action, but it leaves you free to use your own syntax to express and implement resources and actions.
Route in ASP.Net MVC is a pattern matching string that represents the absolute path of a URL. The route doesn’t include protocol, server and port information. It can be constant string or combination of constant and placeholder or only placeholder(s).
When you develop your ASP.Net MVC application you often come across a File available in App_Start Folder by the name RouteConfig.cs. The static RegisterRoutes method defines the pattern and the order in which ASP.Net MVC runtime examines the URL to process the request. Routes are registered through Global.asax file at application startup. If you go to Global.asax.cs you will find a call to the static method RegisterRoutes of RouteConfig. routes.MapRoute method adds the routes to the static collection defined by RouteTable.Routes.
Please note since the order of registering the route is important register them from most specific to the least specific. Once the rules are specified to check whether the URL is accepted the RouteHandler comes into play. It implements IRouteHandler interface.
public interface IRouteHandler{ IHttpHandler GetHttpHandler(RequestContext requestContext);}
The requestContext class encapsulates the HttpContext and route specific data in RouteData object. Although we have devised a way to come out from the dependency the request had on physical resources i.e. aspx in ASP.Net Web Form application but what if we want our URLs to work for physical files also. By default this setting is disabled in ASP.Net MVC Application even if route exists for such URL but if we want to can enable it by setting routes.RouteExistingFiles = true in RegisterRoutes method.
Additinally if you don’t want some URLs to be processes add them via IgnoreRoute method. All that IgnoreRoute does is associate a StopRoutingHandler route handler to the route built around the specified URL pattern.

ASP.Net MVC: How Microsoft has explained the foundation correlating with ASP.Net web forms.



ASP.Net MVC: How Microsoft has explained the foundation correlating with ASP.Net web forms.

If you are from ASP.Net Web Forms background. You must have noticed that the request was based on two parts the physical location of the file (e.g.http://localhost:8090/MyFirstPage.aspx) whose code-behind contains the logic and some data passed via query string(FirstName and LastName passed as querystring  such as http://llocalhost:8090/MyFirstPage.aspx?FirstName=Ashish&LastName=Kalra). This doesn’t mean that all the requests were possible by this mode only. If you want to have some different request scheme you implement your adhoc custom handler. Thus earlier also you can use ASP.Net to handle request regardless of the dependencies on physical files.
Also people often get confused between URN, URI and URL. Let’s quickly erase this doubt. URI (Uniform Resource Identifier) is used to refer to a resource by location or a name. When the URI identifies the resource by location it’s called URL (Uniform Resource Locator).When the URI identifies the resource by name it become URN (Uniform Resource Name). I was also elated when I learned this. Thanks to Microsoft books.
So if you examine carefully you come to one conclusion. Although you can have user friendly URLs in ASP.Net web forms world but it comes at the cost of hard coding all the combination and mapping the combination in web.config.ASP.Net MVC came up with the flexible syntax by adding a new component in the runtime pipeline (which intercepts requests, processes the URL and triggers the ASP.NET MVC HTTP handler), known as URL routing HTTP Module. To be more precise in ASP.NET MVC, URL rout­ing serves the purpose of mapping incoming URLs to a controller class and an action method. Don’t worry we will come to the controller and action later on. But for now consider Controller as a class and action as one of the class method.
Never forget MVC is just a design pattern which produced a new framework-ASP.Net MVC. This framework takes use of the same ASP.Net runtime which ASP.Net web forms is using. ASP.Net MVC is a loosely coupled architecture where maintainability as well as testability of the solutions is easier to perform.
The URL routing HTTP module supersedes the URL rewriting feature of older versions of ASP.NET. URL rewriting exists to decouple the requested URL from the physical webpage that serves the request. There is a very good article in code project written by one of techie Rahul Rajat Singh explaining how to perform URL rewriting using custom HTTP module. http://www.codeproject.com/Articles/335968/Implementing-HTTPHandler-and-HTTPModule-in-ASP-NET Please go through it to have an idea of how URL rewriting can be done in ASP.Net web forms.
Thus all we can conclude whenever a request pertaining to an application hosted in IIS comes to the IIS.URL routing module intercepts the request that couldn’t be served via old way of custom handler and custom module. e.g. if the request is for .aspx page or extension mapped with IIS the request is processed in terms of page handler. If the request is like Home/Projects and a custom handler exists then also the request is processed via custom handler. For other requests URL routing module comes into play and the request goes into ASP.Net MVC space. If still the request can’t be processed then Http 404 Error occurs. Conclusion is in ASP.Net MVC space the request that match predefined URL patterns are allowed to take advantage of ASP.Net MVC runtime. All such requests are routed to the common HTTP handler class that instantiates the appropriate controller class and then invokes the action method on it. The rest is all MVC patterns i.e. Model, View and Controller around which the story of entire ASP.Net MVC application revolves.

HTTP Handler

Have you ever thought what happens when a request comes to IIS. Sending a request and serving the request with a response actually has lot of activities involved.

Infact the way request is processed is different for IIS versions also.
In IIS 5.0 and IIS 6.0 there are two seperate pipelines involved.
While in the case of IIS7.0 you have an option of choosing whether two pipelines are required or you want only one integrated pipeline to do the work.

Lets first examine How it works in IIS5.0 and IIS6.0
Inside the IIS, ISAPI(Internet Server Application Programming Interface) extensions are implemented.So when the request comes the IIS determines which ISAPI extension can process the request based on the file name extension.
e.g. If the request is for AspNetLovers.aspx then ASP.Net will handle the request because ASP.Net is the ISAPI Extension for aspx pages. There are others which are also mapped to ASP.Net extension e.g. request for .ascx, .ashx, and .asmx files.This means that the request for static pages e.g. .html files will not be able to take advantage to ASP.Net ISAPI Extension. We also understand this as ASP.Net has handlers for .aspx,.ascx,.ashx and .asmx files. In case of other types of files since there is no extension we need to create one. This doesn't mean that .htm file will not be rendered when hosted inside IIS. They will be rendered as they are static contents but they can't take advantage of ASP.Net ISAPI extension features.The reason is:If IIS doesn't find the appropriate handler default StaticFileHandler tries to process the request.

Thus we got to know why we need handler. As described above requests which cannot be handled by ASPNet ISAPI extension needs to be handled via creating our own custom handler and registering the handler in webconfig file and IIS.

Enough with the discussion part let's do some practical for it.
We are building an application where if the user requests the file which cannot be handled even by the default handler then an error message is displayed.
namespace DemoForHTTPHandlerAndHTTPModule
{
    public class CustomHandler:IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)

        {
            if (!(context.Request.Url.AbsolutePath.EndsWith(".aspx")))
            {
                context.Response.Write("Error..Please type a valid aspx page");
            }
        }
    }
}
 Registering of Handler in web.config For Integrated Pipeline:

<configuration>
  <system.webServer>
    <handlers>
      <!--<add verb="*" path="*.cspx" type="DemoHttpHandlersAndModules.CspxHandler" name="MyHandler"/>-->
    <add verb="*" path="*.cspx" type="DemoForHTTPHandlerAndHTTPModule.CustomHandler" name="CustomHandler"/>
    </handlers>
  </system.webServer>
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>


Add a webform in the solution say:FrmTestHandler.aspx
Now run the solution setting FrmTestHandler.aspx as the start page.

Fig 1.1 FrmTestHandler.aspx