Using context switching for a different output
Not only do we want to be able to output the content through different view strategies, we sometimes also want to do this on demand, so that we can switch the output, for example, from HTML to JSON by simply changing the headers in our request.
Getting ready
In some cases (for example, in the REST servers) it is necessary to switch the response output of the content depending on what the user asks for. The user can add an Accept
header to let the server know which output formats it accepts, for example application/json
, and text/html
.
What we are going to do is create a simple website that will output a text/html
format on default (which is normal), but it will also output a JSON string whenever we have Accept: */json
in our header.
How to do it…
Sometimes we want to cater not just to the users that view our website, but to a lot of different audiences, for example, the Feed readers or other applications. Therefore we'll discuss how to switch contexts...