Unit 6
Unit 6
Unit 6
1
STATE MANAGEMENT ON STATELESS HTTP
HTTP is a stateless protocol. So, HTTP requests are independent messages that don’t retain user
values or app states. We need to take additional steps to manage state between the requests.
State can be managed in our application using several approaches.
15
CACHE CLIENT-SIDE STRATEGIES
COOKIES,
QUERY STRINGS,
HIDDEN FIELDS
16
Cookies
Reading Cookie
//read cookie from IHttpContext Accessor
string cookieValueFromContext =
httpContextAccessor.HttpContext.Request.Cookies["key"];
Remove Cookie
Response.Cookies.Delete(key);
17
Cookies
Writing cookie
In this example, SetCookie method show how to write cookies.
CookieOption is available to extend the cookie behavior.
public void SetCookie(string key, string value, int? expireTime) {
CookieOptions option = new CookieOptions();
if (expireTime.HasValue)
option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
else
option.Expires = DateTime.Now.AddMilliseconds(10);
Response.Cookies.Append(key, value, option);
}
18
Query strings
We can pass a limited amount of data from one request to another by adding it to
the query string of the new request. This is useful for capturing the state in a
persistent manner and allows the sharing of links with the embedded state.
public IActionResult GetQueryString(string name, int age) {
User newUser = new User()
{
Name = name,
Age = age
};
return View(newUser);
}
19
Query strings
Now let’s invoke this method by passing query string parameters:
/welcome/getquerystring?name=John&age=31
20
Query strings
We can retrieve both the name and age values from the query string and
display it on the page.
As URL query strings are public, we should never use query strings for
sensitive data.
22
[HttpGet]
};
return View(newUser);
[HttpPost]
var id = keyValues["Id"];
return View();
}
23
Hidden Fields
The GET version of theSetHiddenValue() method creates a user object and passes
that into the view.
We use the POST version of the SetHiddenValue() method to read the value of a
hidden field Id from FormCollection.
In the View, we can create a hidden field and bind the Id value from Model:
◦ @Html.HiddenFor(model =>model.Id)
25
Hidden Fields
On inspecting the page source, we can see that a hidden field is generated on the page
with the Id as the value: <input id="Id" name="Id" type="hidden" value="101">
Now click the submit button after putting a breakpoint in the POST method. We can
retrieve the Id value from the FormCollection
Since the client can potentially tamper with the data, our application must always
revalidate the data stored in hidden fields.
26
Discussion Exercise
1. Write about the State Management Strategies.
2. What is Session State? Show with an example to manage session state in
ASP.NET Core.
3. Show the difference between TempData and Using HttpContext with suitable
example.
4. How do you manage to handle state with client side strategies?
27