Tuesday, October 29, 2024

Host attribute on action method in ASP.NET Core

The Host attribute in ASP.NET Core is used to specify a route constraint for a specific host or set of hosts that should match a particular action method. This allows routing based on the hostname, making it useful when you need to handle requests differently based on the domain or subdomain used in the URL.

Host attribute Basic Usage in ASP.NET Core:
You can apply the Host attribute directly on an action method or controller to specify the allowed host(s).

[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    [Host("example.com")]
    public IActionResult GetFromExampleHost()
    {
        return Ok("Accessed from example.com");
    }

    [HttpGet]
    [Host("subdomain.example.com")]
    public IActionResult GetFromSubdomain()
    {
        return Ok("Accessed from subdomain.example.com");
    }

    [HttpGet]
    public IActionResult GetFromAnyHost()
    {
        return Ok("Accessed from any host");
    }
}
In this example:
  • GetFromExampleHost is only accessible when the request is made to example.com.
  • GetFromSubdomain is accessible when the request is made to subdomain.example.com.
  • GetFromAnyHost is accessible from any host since it does not have the Host attribute applied.
Using Wildcards
The Host attribute also supports wildcards, which can be helpful when dealing with subdomains or variable host names.

[HttpGet]
[Host("*.example.com")]
public IActionResult GetFromAnySubdomain()
{
    return Ok("Accessed from any subdomain of example.com");
}
In this case, any subdomain of example.com (e.g., blog.example.com, shop.example.com) would match this route.

Using Multiple Hosts
You can specify multiple hosts in the Host attribute, allowing the action to be accessible from more than one hostname.

[HttpGet]
[Host("example.com", "another-example.com")]
public IActionResult GetFromMultipleHosts()
{
    return Ok("Accessed from example.com or another-example.com");
}

This method will be accessible from both example.com and another-example.com.

Benefits
  • Multi-tenant Applications: Allows different responses based on the host, which is helpful in multi-tenant applications.
  • Security and Separation: Provides a way to restrict specific routes to certain hosts, enhancing security and flexibility.
  • Customization: Allows for custom handling of routes based on host, which is useful for sites with multiple domains or subdomains.

No comments:

Post a Comment

Hot Topics