Home > Software design >  Cannot use a single class instance to update class variables in Web API controller methods
Cannot use a single class instance to update class variables in Web API controller methods

Time:10-30

First time posting here so could be a little vague.

I recently started working on .NET Web API and was trying to create controller class for the API. In the controller class I wanted to instantiate an object of a class(lets say class GetLabels) whose methods will be used to modify variable of the class(in my case want to modify a dictionary of the GetLabels class which is private).

[Route("api/[controller]")]
    [ApiController]
    public class ConnectionController : ControllerBase
    {
        GetLabels getLabels;
        public ConnectionController()
        {
            getLabels = new GetLabels;
        }
    
        // Post: api/Connection/
        [HttpPost]
        public  IActionResult BuildLabels()
        {

             getLabels.Add(key,value);// a public method Add() of class GetLabels adds a key to the dictionary   
              
        }
        
        [HttpPost"{id}"]
        public  IActionResult RemoveLabels()
        {
  
            getlabels.Remove(key,value);// a public method Remove() of class GetLabels deletes the previously added key from the dictionary  
         
        }     
    }

When I run the Put methods one after another(first add and then delete), on the second put method I get empty dictionary even though I using the same instance of the class for both the controller methods. What I am doing wrong over here.

CodePudding user response:

The life-cycle of controller in .NET Web API is created per request. Every time you call a request from this controller, the following code is executed:

    public ConnectionController()
    {
        getLabels = new GetLabels;
    }

In fact, you add the label to one instance of the class, and you want to remove it from another instance.

CodePudding user response:

The RESTful architecture with Asp.net works in a stateless way.

The server cannot take advantage of any context stored on the server.

The use of the server cache is possible : Is it possible to create stateful web service in C#?

  • Related