How To Change URLs In ASP.NET Core MVC?

How To Change URLs In ASP.NET Core MVC?

In ASP.NET Core MVC, you can change the URL of a page by using the Redirect method of the Controller base class. This method takes a string parameter representing the target URL, and sends a redirect response to the client with the specified URL.

For example, suppose you have a controller action that handles a form submission and needs to redirect the user to a different page upon successful submission. You could do this by calling the Redirect method in the action:

public IActionResult FormSubmit() 
{ 
    // Process form submission 
     return Redirect("/form-success"); 
} 

Alternatively, you can use the RedirectToAction method to redirect to a different action in the same or a different controller. This method takes the name of the action and the name of the controller as parameters:

public IActionResult FormSubmit() 
{ 
    // Process form submission 
     return RedirectToAction("Success", "Home"); 
} 

Both of these methods will send a HTTP 302 status code to the client, indicating that the requested resource has temporarily moved to a different location. The client will then issue a new request to the specified URL.

You can also use the RedirectPermanent method to send a HTTP 301 status code, indicating that the resource has permanently moved to a new location. This can be useful for implementing URL redirects when you are changing the URL of a page or moving content to a new location.

public IActionResult FormSubmit() 
{ 
    // Process form submission 
     return RedirectPermanent("/form-success"); 
} 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *