Reputation: 534
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
}
}
Upvotes: 0
Views: 253
Reputation: 23690
Assuming that the value of _reqState
is not changed between the invocation of your Action method (Get()
) and then conditional check, or in your controller constructor - then yes the condition is always true.
public class ProductsController : ApiController {
public ProductsController()
{
// As long as _reqState is not changed here
}
private int _reqState = -1;
public object Get(int id) {
// ... or here
if (_reqState == -1} {} //condition #1 - always true
//DO SOME WORK WITH _reqState
}
}
The value set for _reqState
is not carried across multiple requests as the controller is created and destroyed with each request.
So the value of _reqState
is not the same instance of the variable each time, it's a newly set -1
value.
Upvotes: 0
Reputation: 156988
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;
}
}
Upvotes: 1