Skip to main content

How is Routing done in ASP.Net MVC

How routing is done in asp.net mvc
Each route contains the following info,
1. the url
2. the curly braces that specify the match
3. the constraints for the inputs in the url parameters
Each route should be anything that inherits from the RouteBase.
****************
foreach route in the routescollection do,
{
1. The url in the route should match the incoming url
2. The contents for the curly braces must match in the incoming url
3. The constraints should also match with the route taken from the
routes collection.
4. If a match occurs, then the route is considered as a valid one
}
for every route match to be done, the routebase supplies the URL, the
curlybrace dictionary with its replacement from the request URL, route
parameter values with the optional ones for which no value was
received from the i/p request.
3. The route handler is passed with the requestContext [url, cookies,
authentication data, request data etc]
once a first route match is done, the routing mechanism stops finding
the next match thereafter
The values for the action method parameters are taken from the
RouteData's values. Ex: RouteData.Values["name"] will be used for an
action method like public ActionResult GetUserData(string
name){..........}
To mark a parameter as optional in a route, set the route as follows,
routes.MapRoute("","Catalog/{color}", new {controller="catalog",
action="list", color=(string)null});
Here the (string)null is to specify that a null is used for a string
datatype parameter.

HttpVerbConstraints
*******************
RouteConstraints to restrict HTTPGet an HTTPPost methods,
this can be done via the attributes on the action methods or can be
done in the routing level itself. If done in the routing level, the
constraint is applied at an earlier stage in the pipeline than the
attributes in the action methods.

Constraints
**********
When a constraint failed, then the route next to the that evaluates to
false is evaluated.
sample:
var ieOnlyRoute = new Route("Customer/Edit", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit"
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE"),
cookieConstraint = new CookieConstraint()
})
};
Also it is possible to map controllers from a different namespace, sample
To accept any number of segments in the url, use the catchall
parameter in the route config in global.asax as follows,
var ieOnlyRoute = new Route("Customer/Edit/{*ArticlePath}", new
MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit"
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE")
}),
DataTokens = new RouteValueDictionary(new
{
Namespace = new[] { "MvcApplication11.Controllers" }
})
};
To enable the file access also to be routed instead of rendering it
dierectly use the following route setting in the global.asax after 1
or more routes are registered there.
routes.RouteExistingFiles = true;
To render the content files only of specific folder the following
settings can be used in the global.asax.cs
routes.RouteExistingFiles = true;
routes.IgnoreRoute("Content/{file}.{abc}");
routes.IgnoreRoute("Content/{*restOfTheUrl}");
The above 2 lines are equivalent to routes.Add(new
Route("Content/{file}.{abc}", new StopRoutingHandler());
********************************************************************************************

Handling the Outgoing URL's
*************************
The way in which the Html.ActionLink renders the url parameters is
based on the routing defitions

Sample1 [w/o explicit routing]
*************************
var ieOnlyRoute = new Route("Customer/Edit/{*ArticlePath}", new
MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit"
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE")
//,cookieConstraint = new CookieConstraint()
}),
DataTokens = new RouteValueDictionary(new
{
Namespace = new[] { "MvcApplication11.Controllers" }
})
};
For this routing configuration, the links generated are looking like
<a href="/Customer/Edit?id=firstname">Edit</a>

However, if the above routing configuration is modified to incorporate
the id parameter in the url parameter, the rendered markup will vary
as follows,
var ieOnlyRoute = new Route("Customer/Edit/{id}/{*ArticlePath}", new
MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
controller = "Customer",
action = "Edit",
id = UrlParameter.Optional
}),
Constraints = new RouteValueDictionary(new
{
userAgent = new BrowserConstraint("MSIE")
//,cookieConstraint = new CookieConstraint()
}),<%: Html.ActionLink("Click me", "MyAction",
"MyController", "https",
"www.example.com", "anchorName", new { param = "value" },
new { myattribute = "something" }) %>
DataTokens = new RouteValueDictionary(new
{
Namespace = new[] { "MvcApplication11.Controllers" }
})
};
Now, the markup rendered will look like,
<a href="/Customer/Edit/firstname">Edit</a>

This makes the difference and gets the clean url.

To generate the fully qualified URL's, refer the overloads of the
ActionLink method that takes the domain, uri scheme etc to generate a
fully absolute URL.
<%: Html.ActionLink("Click me", "MyAction", "MyController", "https",
"www.example.com", "anchorName", new { param = "value" },
new { myattribute = "something" }) %>

Routing is never associated with the Absolute URL's, it always renders
or deals with the Absolute URL's
However, the Html.RouteLink can take the protocol and domain values to
generate the urls that are absolute as generated by the actionlink
helper methods.

RouteURL API to genertate links from route data instead of using action links

1. <%: Url.RouteUrl(new { controller = "Products", action = "List" }) %>
2. return RedirectToRoute(new { action = "SomeAction", customerId = 456 });
3. <%: Html.RouteLink("Delete",new{action= "Delete", id=item.FirstName })%>

Areas
*****
InboundURL
**********
W.r.to areas, it is found that the areaContext's MapRoute API sets the
namespace of the route inthe DataTokens["Namespaces"] configuration
for the route. Hence, when resolving a URL, the framework searches for
the controller in the Namespaces part of the route definiton and does
not resolve a controller from another area or from the base root
directory.

Outbound URL
************
To facilitate this, it uses the DataTokens["area"] to store the name
of the area.

Links between Areas
*****************
To link between 2 areas, use the area property of the
routevaluedictionary and se tthe are nmae so tha the URL points to the
specified area than the current area.

To jump from the area to the root controllers, we have to provide a
(string)null in the area parameter in the routevaluedictionary.

Comments

Popular posts from this blog

User Authentication schemes in a Multi-Tenant SaaS Application

User Authentication in Multi-Tenant SaaS Apps Introduction We will cover few scenarios that we can follow to perform the user authentication in a Multi-Tenant SaaS application. Scenario 1 - Global Users Authentication with Tenancy and Tenant forwarding In this scheme, we have the SaaS Provider Authentication gateway that takes care of Authentication of the users by performing the following steps Tenant Identification User Authentication User Authorization Forwarding the user to the tenant application / tenant pages in the SaaS App This demands that the SaaS provider authentication gateway be a scalable microservice that can take care of the load across all tenants. The database partitioning (horizontal or other means) is left upto the SaaS provider Service. Scenario 2 - Global Tenant Identification and User Authentication forwarding   In the above scenario, the tenant identification happens on part of the SaaS provider Tenant Identification gateway. Post which, ...

Handling exceptions in the Executor service threads in Java

Introduction This is a continuation post on the exception handling strategies in the threads in Java. For Introduction, please read this post The second post is available here This post addresses the problem statement "How to use the exception handlers in the threads spawned by the Executor Service in Java?" Not all times, we will be using Thread  classes to run our threads because we have to manage a lot of the underlying logic for managing threads. There is ExecutorService in Java which comes to the rescue for the above problem. In the previous posts, we have discussed on how to handle the exceptions in plain threads. However, when using executor service, we do not create / manage threads, so how do we handle exception in this case. We have a ThreadFactory   as an argument which can be used to customize the way threads are created for use within the ExecutorService . The below snippet of code leverages this feature to illustrate the exception handling, wherein we creat...

Upgrade from http1.1 to http2 for Java spring boot applications hosted in tomcat

In this post, we will list down the tasks to be done for enabling the HTTP 2.0 support in spring boot applications which are hosted in Apache tomcat webserver Application Level Changes Spring boot Application Configuration Changes server.http2.enabled=true In the spring boot application's application.properties file, we have to add the above line so that Spring boot can add the support for http2 Tomcat server configuration In the tomcat web server, we should have SSL enabled before doing the below change. To start with, we have to shutdown the tomcat server instance that is running CD to the directory that has tomcat installed and cd to the bin directory and run the below command sh shutdown.sh We have add the UpgradeProtocol  which adds the respective Http2Protocol handler classname to the connector pipeline that enables support for http2.0 <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" /> The above UpgradeProtocol can be added to the connec...

SFTP and File Upload in SFTP using C# and Tamir. SShSharp

The right choice of SFTP Server for Windows OS Follow the following steps, 1. Download the server version from here . The application is here 2. Provide the Username, password and root path, i.e. the ftp destination. 3. The screen shot is given below for reference. 4. Now download the CoreFTP client from this link 5. The client settings will be as in this screen shot: 6. Now the code to upload files via SFTP will be as follows. //ip of the local machine and the username and password along with the file to be uploaded via SFTP. FileUploadUsingSftp("172.24.120.87", "ftpserveruser", "123456", @"D:\", @"Web.config"); private static void FileUploadUsingSftp(string FtpAddress, string FtpUserName, string FtpPassword, string FilePath, string FileName) { Sftp sftp = null; try { // Create instance for Sftp to upload given files using given credentials sf...

Download CSV file using JavaScript fetch API

Downloading a CSV File from an API Using JavaScript Fetch API: A Step-by-Step Guide Introduction: Downloading files from an API is a common task in web development. This article walks you through the process of downloading a CSV file from an API using the Fetch API in JavaScript. We'll cover the basics of making API requests and handling file downloads, complete with a sample code snippet. Prerequisites: Ensure you have a basic understanding of JavaScript and web APIs. No additional libraries are required for this tutorial. Step 1: Creating the HTML Structure: Start by creating a simple HTML structure that includes a button to initiate the file download. <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title > CSV File Download </ title > </ head > < body > ...