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, the

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 >

Implementing Row Level Security [RLS] for a Multi-Tenant SaaS Application

Row Level Security The need for row level security stems from the demand for fine-grained security to the data. As the applications are generating vast amounts of data by the day. Application developers are in need of making sure that the data is accessible to the right audience based on the right access level settings. Even today, whenever an application was built, the application development team used to spend a lot of time researching the approach, implementing multiple tables multiple logics 25 queries to add filters to manage the data security for every query that gets transferred from the end user request to the application database. This approach requires a lot of thought process, testing and security review because the queries needs to be intercepted, updated and the data retrieval to be validated to make sure the end-users see only the data that they are entitled to. Implementation With the advent of of row level security feature being rolled out in main d

Async implementation in Blazor

Step-by-Step Guide to Achieving Async Flows in Blazor: 1. Understanding Asynchronous Programming: Before delving into Blazor-specific async flows, it's crucial to understand asynchronous programming concepts like async and await . Asynchronous operations help improve the responsiveness of your UI by not blocking the main thread. 2. Blazor Component Lifecycle: Blazor components have their lifecycle methods. The OnInitializedAsync , OnParametersSetAsync , and OnAfterRenderAsync methods allow you to implement asynchronous operations during various stages of a component's lifecycle. 3. Asynchronous API Calls: Performing asynchronous API calls is a common scenario in web applications. You can use HttpClient to make HTTP requests asynchronously. For example, fetching data from a remote server: @page "/fetchdata" @inject HttpClient Http @ if (forecasts == null ) { <p> < em > Loading... </ em > </ p > } else { <table>