(C# ASP.NET Core 5)How to restrict access ONLY to requests from a specific list of domains and ports only

Write an ASP.NET Core application such that the route "/home/index/N", where N is any int number, executes only if the website is hosted on port 67291 of "hoven.in" or "www.hoven.in". It should return 404 even if it is hosted on any subdomain like "*.hoven.in:67291"?

Categories | About |     |  

Parveen,

Solution in Brief

Set the Host attribute on the action method to allow access only from a specific collection of hosts. The collection is comma separated.

An optional port number can be included. If the collection is empty then ANY host is permitted.

In the following code, the "Index" method can be reached only through the routes that have one of the three hosts - hoven.in:67291, www.hoven.in:67291 and localhost.

// routes permitted ONLY from one of these three hosts 
[Host("hoven.in:67291", "www.hoven.in:67291", "localhost")]
public IActionResult Index(int? id)
{

  // code goes here 
}

Details of the HostAttribute class are available here - HostAttribute Class on MSDN

Code for the Startup.cs file

Create an ASP.NET Core project based on an empty template. Edit the Startup class like this

public class Startup
{

  public void ConfigureServices(IServiceCollection services)
  {

    services.AddMvc();

  }

  public void Configure(IApplicationBuilder app)
  {

    app.UseRouting();

    app.UseEndpoints(endpoints =>

    {

      endpoints.MapControllerRoute
      (
      pattern: "/{controller}/{action}/{id?}",
      defaults: new { controller = "Hoven", action = "Index" },
      constraints: new { id = "int" },
      name: "MyRoute"
      );

    });

  }

}

Code for the Controller

public class HovenController : Controller
{

  // [Host("hoven.in:67291", "www.hoven.in:67291", "localhost")] 
  [Host("hoven.in:67291", "www.hoven.in:67291")]
  public IActionResult Index(int? id)
  {

    return new ObjectResult("Hello, MVC!");

  }

}

Comments and Discussion

Please write your comments and discussion on the following youtube video itself:


This Blog Post/Article "(C# ASP.NET Core 5)How to restrict access ONLY to requests from a specific list of domains and ports only" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Comments and Discussion