Search code examples
c#asp.net-mvcasp.net-apicontroller

An object of ApiController for each request ASP.NET


Will a new object of API Controller creating after each request to the page?

So I need to know if condition #1 is always true or not?

public class ProductsController : ApiController {
    private int _reqState = -1;

    public object Get(int id) {
        if (_reqState == -1}  {} //condition #1
        //DO SOME WORK WITH _reqState
    }
}

Solution

  • Yes, a controller has a short lifetime, just for this request. After that it is disposed and your value is lost.

    If you want to keep some state, you have to use Session, Application or an external storage to save your state.

    For example:

    private int ReqState
    {
        get
        {
            return (this.HttpContext.Session["ReqState"] as int?).GetValueOrDefault(-1);
        }
        set
        {
            this.HttpContext.Session["ReqState"] = value;
        }
    }