301 HTTP Status Code in ASP.NET Core Web API

301 HTTP Status Code in ASP.NET Core Web API

In this article, I will discuss How to Return 301 Moved Permanently HTTP Status Code from the ASP.NET Core Web API Controller Action method with Examples. Please read our previous article discussing How to Return 204 HTTP Status Code in ASP.NET Core Web API with Examples.

301 HTTP Status Code

The 301 HTTP Status Code stands for “Moved Permanently.” It indicates that a resource has been permanently moved to a new location. When a server returns this status code, it also provides the new URL in the response headers under Location, and all future requests should use the new URL provided in the response.

It’s commonly used when a website or a web page has been moved, and you want to make the transition seamless for users and search engines. The following are some of the key points about the HTTP 301 status code:

  • Permanent Redirect: It informs the client that the resource has been permanently moved to a different URL.
  • Browser Behavior: Browsers will cache the redirection, meaning subsequent requests for the old URL will automatically be redirected to the new URL without another server request.
  • Headers: The response includes a Location header with the new URL.
How Do We Return 301 HTTP Status Code in ASP.NET Core Web API?

In the context of an ASP.NET Core Web API, we would typically use this status code to inform clients (such as web browsers or other consuming applications) that the resource they are trying to access has been moved to a different URL and they should update the URLs they use to access the resource. We can implement this in 3 ways in ASP.NET Core Web API. They are as follows:

  • Using RedirectPermanent Method.
  • Manually Creating a RedirectResult with a 301 Status Code.
  • Setting StatusCode and Location Header Manually.
RedirectPermanent Method:

The RedirectPermanent method is a built-in helper method that provides a convenient way to issue a 301 (permanent) redirection. The RedirectPermanent helper method is part of the ControllerBase class, making it readily accessible within any controller action. It is best when you want a quick and straightforward permanent redirection without needing to customize other response headers. Automatically handles the status code and Location header. For a better understanding, please modify the Employee Controller as follows:

using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet("old-route")]
        public IActionResult GetFromOldRoute()
        {
            // The URL of the new location for the resource
            //string newUrl = "https://localhost:7128/api/Employee/new-route";
            string newUrl = Url.Action("GetFromNewRoute", "Employee");

            // Redirects permanently to the new URL with a 301 HTTP status code
            return RedirectPermanent(newUrl);
        }

        [HttpGet("new-route")]
        public IActionResult GetFromNewRoute()
        {
            // Code to handle the request at the new location
            return Ok("This is the new location for the resource.");
        }
    }
}

In this example, any request to /api/employee/old-route will be permanently redirected to /api/employee/new-route with a 301 Status Code. This tells the client that the resource at the old route has moved permanently to the new route, and future requests should be made directly to the new URL.

Now, if you make a request to the /api/employee/old-route, then it will get a 301 Moved Permanently response, and then immediately, it will call the new URL. So, to understand this better, open the Fiddler tool and make a Get Request to the /api/employee/old-route URL as shown in the below image:

How to Return 301 Moved Permanently HTTP Status Code from the ASP.NET Core Web API Controller Action method with Examples

Once you click on the Execute button, you will see. First, it will execute the /api/employee/old-route URL and will get the 301 response, and then immediately it will execute the /api/employee/new-route from where it will get the actual response as shown in the below image:

How to Return 301 Moved Permanently HTTP Status Code in ASP.NET Core Web API

Now, if you open the api/employee/old-route URL by double-clicking on it, you will see the following in the Response header, as shown in the image below.

How to Return 301 HTTP Status Code in ASP.NET Core Web API

Now, if you open the api/employee/new-route URL by double-clicking on it, then you will see the actual data in the Response body, as shown in the image below.

301 HTTP Status Code in ASP.NET Core Web API

Note: Once you get the 301 Status Code, you need to replace the OLD URL with the new URL as a client.

Manually Creating a RedirectResult with a 301 Status Code:

This approach offers more control compared to RedirectPermanent. You manually create an instance of RedirectResult, where you can explicitly set the status code, although RedirectPermanent inherently does so for 301. It is useful when you might need to instantiate redirect results conditionally or dynamically in different parts of your code, not necessarily tied to a direct controller response. For a better understanding, please modify the Employee Controller as follows:

using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet("old-route")]
        public IActionResult GetFromOldRoute()
        {
            // The URL of the new location for the resource
            //string newUrl = "https://localhost:7128/api/Employee/new-route";
            string newUrl = Url.Action("GetFromNewRoute", "Employee");

            // Redirects permanently to the new URL with a 301 HTTP status code
            return new RedirectResult(newUrl, permanent: true);
        }

        [HttpGet("new-route")]
        public IActionResult GetFromNewRoute()
        {
            // Code to handle the request at the new location
            return Ok("This is the new location for the resource.");
        }
    }
}
Setting StatusCode and Location Header Manually:

This method provides the most control over the HTTP response. You manually set the status code and the Location header of the response. This requires a deeper understanding of HTTP headers. It is ideal for scenarios where you need full control over the response, such as when additional headers need to be manipulated or when the redirect is conditional based on more complex logic than a simple URL change. For a better understanding, please modify the Employee Controller as follows:

using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet("old-route")]
        public IActionResult GetFromOldRoute()
        {
            // The URL of the new location for the resource
            //string newUrl = "https://localhost:7128/api/Employee/new-route";
            string newUrl = Url.Action("GetFromNewRoute", "Employee");

            // Redirects permanently to the new URL with a 301 HTTP status code
            Response.StatusCode = 301; // HTTP 301 Moved Permanently
            Response.Headers["Location"] = newUrl;
            return new EmptyResult();
        }

        [HttpGet("new-route")]
        public IActionResult GetFromNewRoute()
        {
            // Code to handle the request at the new location
            return Ok("This is the new location for the resource.");
        }
    }
}

Note: Modern web browsers will cache the 301 Redirect Response. Therefore, if you later decide to change the redirect or revert it, users who have already accessed the old URL may not see the change until their cache is cleared.

Differences between RedirectPermanent, RedirectResult, and StatusCode:

Each method has its own strengths, and the best choice depends on your application’s specific requirements. For simple, straightforward redirects, RedirectPermanent is usually sufficient. If you need more customization, manually creating a RedirectResult is a good choice. For advanced scenarios requiring full control over the response, setting the status code and location header manually is the most flexible approach.

how to Return 301 Moved Permanently HTTP Status Code in ASP.NET Core Web API with Examples

When Do We Use 301 HTTP Status Code in ASP.NET Core Web API?

The following are some of the specific scenarios in which you would use a 301 HTTP status code:

  • URL Structure Changes: When the structure of your URLs changes, such as renaming or reorganizing routes, for example, Moving from /products/123 to /items/123.
  • Domain Name Changes: When you change the domain name of your website, for example, from www.olddomain.com to www.newdomain.com.
  • Protocol Changes: When switching from HTTP to HTTPS for better security. For example, Redirecting http://example.com to https://example.com.
  • Content Consolidation: When merging multiple pages or resources into a single page. For example, Redirecting example.com/old-page1 and example.com/old-page2 to example.com/new-page.
  • SEO Improvements: To avoid duplicate content penalties, redirect old or duplicate URLs to a canonical URL. For example, Redirect example.com/page and example.com/page/index.html to example.com/page.

In the next article, I will discuss how to Return 302 HTTP Status Code in ASP.NET Core Web API with Examples. In this article, I try to explain how to Return 301 Moved Permanently HTTP Status Code in ASP.NET Core Web API with Examples. I hope you enjoy this article on “301 Moved Permanently HTTP Status Code in the ASP.NET Core Web API.”

Leave a Reply

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