Search code examples
c#.net-coreasp.net-core-mvc

.NET Core : Get parameter value in controller's constructor


I have gone through this solution but this is not what I am looking for get parameters from URL in controller constructor.

Let's say, In an ASP.NET Core Controller I'm requesting to some methods. Let's say the controller is something like:

public class ClassroomsController : Controller {

    private string requestedUserId;

    // C O N S T R U C T O R
    public ClassroomsController()
    {
        /**** THIS POINT ***/
        requestedUserId = ;
    }

    [HttpGet("Classrooms/API01/{userId}")]
    public IActionResult API01(string userId)
    {

    }

    [HttpGet("Classrooms/API02/{userId}")]
    public IActionResult API02(string userId)
    {

    }
}

What I want is whether I request in Classrooms/API02 or Classrooms/API01 the requestedUserId should be initiated inside the constructor based on the parameter userId in both API01 and API02;


Solution

  • What I want is whether I request in Classrooms/API02 or Classrooms/API01 the requestedUserId should be initiated inside the constructor based on the parameter userId in both API01 and API02

    Short Answer: Not Possible.

    All request related logic needs to happen within the action itself.

    public class ClassroomsController : Controller {
    
        // C O N S T R U C T O R
        public ClassroomsController() {
            //...
        }
    
        [HttpGet("Classrooms/API01/{userId}")]
        public IActionResult API01(string userId) {
            string requestedUserId = userId;
    
            //...
        }
    
        [HttpGet("Classrooms/API02/{userId}")]
        public IActionResult API02(string userId) {
            string requestedUserId = userId;
    
            //...
        }
    }
    

    If there is some common functionality that needs to be invoked, then move that to a method that can be called by the controller actions when invoked.