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 HTTP status code 301, known as “Moved Permanently,” is a response code that indicates that the requested resource has been permanently moved to a new URL. When a web server returns this response, it also provides the new URL in the location header of the HTTP response. Clients, such as web browsers or search engines, are expected to update their links to the resource by replacing the old URL with the new one provided. The following are the key characteristics of 301 HTTP Status Code:

  • Definition: Indicates that the requested resource has been permanently moved to a new location.
  • Purpose: Used by web servers to inform the client that the resource they are trying to access has been permanently moved to a new URL. It is an effective way to redirect traffic from an old URL to a new one without losing search engine rankings.
  • Location Header: Accompanied by a ‘Location’ header, which contains the URL of the redirected resource. Clients are expected to follow this new URL to access the resource.
  • SEO Impact: A 301 redirect is crucial for maintaining search engine rankings. When a URL is changed, a 301 redirect ensures that links pointing to the old URL contribute to the link equity of the new URL, preserving its search engine ranking.
  • Usage: Typically used in website migration scenarios, URL structure changes, or when content is permanently moved to a new location.
  • Client Behavior: Upon receiving a 301 Status Code, web clients (browsers) automatically follow the redirect to the new URL provided in the location header, usually without user intervention.
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 their bookmarks or 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:

To return a 301 HTTP Status Code in an ASP.NET Core Web API, we need to use the RedirectPermanent method. This method is useful when we want to redirect requests from one URL to another URL permanently. It tells the client that the resource they are trying to access has been permanently moved to a new location.

This method is the most straightforward way to send a 301 Redirect Response to the client. 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 old-route has moved permanently to 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, then you will see the following in the Response header as shown in the below image.

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, then as a client, you need to replace the OLD URL with the new URL.

Manually Creating a RedirectResult with a 301 Status Code:

If you need more control over the response, you can manually create a RedirectResult object and specify the status code explicitly. 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:

For even more control, you can construct the response manually by setting the StatusCode and Location header. This method is rarely needed, but it’s useful to know it’s possible. 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.

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

In the context of an ASP.NET Core Web API, the 301 Status Code plays an important role in URL redirection strategies, particularly for API versioning, restructuring endpoints, or migrating resources to new paths. Here are specific scenarios in which you would use a 301 HTTP status code:

  • API Versioning: When you release a new version of your API and want clients to use the newer endpoints, you can redirect requests from old endpoints to the corresponding new ones using a 301 Status Code. This approach informs clients that the old endpoint is deprecated and has been permanently moved to a new location.
  • Resource Relocation: If you decide to change the path structure of your API (for example, renaming a resource or changing the hierarchy of endpoints), you can use the 301 Status Code to redirect clients from the old URL to the new URL.
  • Domain Changes: If your API is moving to a new domain, you can use 301 redirects to guide clients from the old domain to the new one, ensuring that API consumers and search engines update their references to your API.
  • Securing Endpoints: If you decide to enforce HTTPS on your API and need to redirect all HTTP requests to HTTPS, a 301 Status Code can redirect clients to the secure endpoint permanently.
  • Link Correction: In case there were typographical errors in the documentation or published URLs that clients might be using, a 301 redirect can be used to correct these without breaking the client’s applications.

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, and 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 *