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)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.