Redirect relates to the routing In ASP.NET. There are two different ways to routing; or changing the current requests endpoint:
Rewrite the current URL and
Redirect to an external URL.
These two tasks are similar but yet different in their execution.
Routing in ASP.Net
Routing in ASP.NET works by mapping incoming URL requests to specific controller actions. When a request is made to a particular URL, the routing system compares the request to a list of route patterns that have been defined in the application. If a match is found, the request is forwarded to the appropriate action on the corresponding controller. If no match is found, the routing system returns a 404 error.
To set up routing in an ASP.NET application, we need to define a route table in the application’s Global.asax file. The route table consists of a collection of Route objects, each of which defines a URL pattern and the corresponding controller and action that should be invoked when a request is made to that URL.
For example, consider the following route definition:
routes.MapRoute(
"ProductDetails",
"products/{productId}",
new { controller = "Product", action = "Details" }
);
This route maps URLs of the form “products/{productId}” to the “Details” action on the “Product” controller. The {productId} parameter in the URL pattern is a placeholder that will be replaced with the actual product ID when a request is made.
In addition to simple parameter placeholders, ASP.NET routing also supports more advanced URL patterns using constraints. Constraints allow us to specify conditions that the parameter values must meet in order for the route to be considered a match. For example, we might specify that the {productId} parameter must be an integer value:
routes.MapRoute(
"ProductDetails",
"products/{productId}",
new { controller = "Product", action = "Details" },
new { productId = @"\d+" }
);
Once we have defined our routes, we can use them in our application by generating URLs using the Html.ActionLink helper method in our views. For example:
@Html.ActionLink("View Product Details", "Details", "Product", new { productId = 123 }, null)
This will generate a link to the “Details” action on the “Product” controller, with the product ID set to 123. When clicked, the link will be routed to the appropriate URL based on the route definitions in our route table.
Rewriting:
Rewriting changes the request’s path and continues processing the request with its existing state through the middleware pipeline. Middleware registered after the rewrite sees the new URL and processes the remainder of the request with the new path. All of this happens in a single server request. One use case might be Creating ‘prettier URLs’.
For example, here’s how to handle a Rewrite operation in app.Use()
middleware:
app.Use(async (context,next) =>
{
var url = context.Request.Path.Value;
// Rewrite to index
if (url.Contains("/home/privacy"))
{
// rewrite and continue processing
context.Request.Path = "/home/index";
}
await next();
});
For more complex rewrite and redirect scenarios we can also use the full-fledged ASP.NET Core Rewrite Middleware. Basically it provides the ability to set regEx
based rewrites and redirects and a number of different and some common rewrite operations.
Redirecting:
Redirecting is the process of directing a user to another URL or page within the application. It is done through an HTTP header response in the browser via an 302 Moved or 301 Moved Permanently HTTP Response header. Redirecting can be done through client-side or server-side methods. Client-side redirecting uses the Response.Redirect method and results in two server requests. Server-side redirecting uses the Server.Transfer method and results in only one server request, but the target URL must be on the same server. Client-side redirecting updates the browser’s address bar, while server-side redirecting does not. Server-side redirecting can potentially break AJAX and JavaScript functionality.
(Client Browser) Response.Redirect:
The Redirect method of the Response object provides a way to implement client-side redirection. The default behavior of the Response.Redirect
method is execution of the current page halts, and the user is sent to the new URL. The Web server issues HTTP headers and sends a 302 response to the client browser; this instructs the client to make redirected calls to the target URL. The result is two server requests for each redirection: the original and redirected requests.
(Web Server) Server.Transfer:
The Transfer method of the Server object performs redirection using the server and avoiding HTTP requests. The Server.Transfer
method transfers the execution of a target URL to the server and halts execution of the current page. The result is only one request. The server does not notify the client browser of the change. And the page address does not change in the browser. When using Server.Transfer
, the target URL must be a virtual path on the same server since the Web server’s worker process is used. The PreviousPage
property of the Page class provides code access to properties of the previous page in the browsing session. So Form
and querystring
variables are persisted between pages.
There are some potential drawback of Server side redirection. For example; The lack of browser interaction with the Server.Transfer
method means it may break some AJAX and/or JavaScript functionality. When users refresh a page located via this approach, it can trigger an invalid ViewState
error message. While Server.Transfer
can cause some user confusion as the URL displayed in the browser address bar is not actually the path that is being executed, it can also lead to some confusion with error logging, as the page URL recorded during logging will display incorrectly.
So most of the cases; the redirect()
method is used for redirecting in ASP.NET. There are more or less 4 variations to this process.
Different Types of Redirect:
Redirect()
The first method of redirecting from one URL to another is Redirect(). The Rediect() method is available to controller from the ControllerBase
class. It accepts a target URL or where we would like to go. A Simple example might be –
public IActionResult Index()
{
return Redirect("~/Home/Privacy");
}
public IActionResult Privacy()
{
return View();
}
RedirectToAction()
The Redirect()
method and its variations accept a target URL that can be internal or external to the web application. On the other hand, RedirectToAction()
is intended specifically for internal URLs that are based on MVC. The RedirectToAction()
method allows us to specify an action name, a controller name, and optionally route values. Consider the following code that uses RedirectToAction()
method.
public IActionResult Index()
{
return RedirectToAction("Privacy", "Home");
}
RedirectToPage()
The RedirectToAction()
method and its variants are intended for MVC applications. There is a set of methods intended for Razor Pages applications. The main method from this group i RedirectToPage()
. RedirectToPage()
method accepts the target Razor Page name. For example, suppose there are two Razor Pages in the Pages folder – Index.cshtml and Privacy.cshtml.
To redirect from Index to Privacy we can write like this in the Onget()
page hander of Index :
public IActionResult OnGet()
{
return RedirectToPage("Privacy");
}
RedirectToRoute()
The RedirectToRoute()
method allows us to specify a route name and route values. It then redirects the control to that route.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/
{action=Index}/{id?}");
});
............................
public IActionResult Index()
{
return RedirectToRoute("default",
new { controller = "Home", action = "Privacy" });
}
LocalRedirect()
The LocalRedirect()
method is similar to the Redirect()
method but can be used to navigate only to the URLs local to our application. That means we can’t redirect to any external / third-party URL using LocalRedirect()
method. The LocalRedirect()
method returns LocalRedirectResult
object and sets the HTTP status code to 302 – Found.
All of the above methods each have 3 variants. They are – Permanent
; PreserveMethod
and PermanentPreserveMethod
. The preserve method is same as original method; but an addition is that they maintain the request method (GET/POST) and also preserves request body.
What is Response.Redirect true and Response.Redirect false?
True and false are the optional parameters of the Redirect methods which decides whether the current page response terminate or not. When we use Response.Redirect("Default.aspx", false)
then the execution of current page is not terminated; instead, the code written after the Response.Redirect
is executed; and then after that page is redirected to the given page. When we use Response.Redirect("Default.aspx",true)
; which is by default true; then the execution of current page is terminated and code written after the Response.Redirect
is not executed instead of executing code written after the Response.Redirect
,the page is redirected to the given page.
The Response.Redirect
method is often used to redirect users to a login page if they are not authenticated, or to a different page after a form submission.
The boolean value passed as the second parameter determines whether the current page execution should be ended after the redirect. If the value is true
, the page execution is ended and the client is redirected to the new URL. If the value is false
, the page execution continues after the redirect.
It is generally recommended to set this value to true
, as ending the page execution can help improve performance and avoid potential issues. However, in some cases it may be necessary to set the value to false
if there is additional processing that needs to be done on the current page after the redirect.
(Note) For mobile pages, if our application relies on cookie-less sessions, or might receive requests from mobile devices that require cookie-less sessions, using a tilde (~) in a path can create a new session and potentially lose session data. To set a property on a mobile control with a path such as “~/path”, we have to resolve the path using ResolveUrl “~/path” before assigning it to the property.
For more posts like this; you might also follow this profile – https://dev.to/asifbuetcse
Happy Coding!