Search code examples
c#apiasp.net-coreasp.net-apicontroller

How to modify the property of a NET API controller class by HTTP methods


I want an API that, whenever the "add" get method is called, an integer will increase by 1. Here's my code:

namespace test.Controllers
{
    [Route("api/[controller]")]
    public class testController : Controller
    {
        private int x;
        public testController(){
            x = 0;
        }

        [HttpGet]
        public JsonResult Get(){return Json(x);}
       

        [HttpGet("add")]
        public JsonResult Add(){
            x++;
            return Json(x);
        }
    }
}

I realize that, if I modify the constructor of the controller class:

public testController(){
            x = 0;
            x++;
}

When I go to the "index", the value of x will be 1. It seems to me that I can change the value of x inside the constructor, but I simply can't change the value of x inside a HTTP method.

I tried to solve the problem by making a "normal" class method, and use the HTTP method to call this method to modify the value of x:

private void add() { x++; }

[HttpGet("add")]
public JsonResult Add(){
    add();
    return Json(x);
}

I thought that, if the constructor method could work, a class method should work as well. However, it still doesn't work. I don't understand why and how could I fix this problem?


Solution

  • A Controller is created for each request, so if you want to increment some persistent data it needs to be stored somewhere else. A static field would work, eg

    namespace test.Controllers
    {
       
    
        [Route("api/[controller]")]
        public class testController : Controller
        {
    
            private static int x = 0;
    
            public testController(){
    
            }
    
            [HttpGet]
            public JsonResult Get(){return Json(x);}
           
    
            [HttpGet("add")]
            public JsonResult Add(){
                x++;
                return Json(x);
            }
        }
    }