JSON from Controller to View in ASP.NET MVC Core and avoid XSS

When working on your ASP.NET MVC application, you often need to include some of your app’s data as Javascript objects. You may need this for some interactive behaviour, graphs/charts, or simply to “hydrate” the UI with the relevant information, such as username etc.

There’s certainly a big push to move away from rendering JSON data in MVC Views. Instead, it’s recommended to use Ajax calls that fetch JSON data from backend APIs. This helps to separate concerns in your application, making it more maintainable and easier to support, test and debug.

However, sometimes it’s OK to put JSON data directly in MVC Views:

  • performance–it saves you another network call
  • prototyping–test your idea before you spend a lot of time on adding another endpoint to your backend API
  • size of the data–if it’s just a small object, you may not want to create a separate endpoint just for that thing
  • legacy–the app you’re working on is ancient, soon-to-be-retired, so there’s really no point putting lipstick on the pig

With these caveats in mind, let’s see how you can easily put some JSON into your ASP.NET MVC views.

Encoding problem

The problem with outputting any values into Views in ASP.NET MVC is that the framework encodes the output, trying to save you from introducing Cross-Site Scripting (XSS) vulnerabilities to your front-end code.

Briefly, an XSS vulnerability is when an attacker can provide some content that has a malicious Javascript payload, which then gets rendered by your web app and executed in users’ browsers.

Check out “Prevent Cross-Site Scripting (XSS) in ASP.NET Core” for more details on how to avoid this happening to your app.

The encoding that ASP.NET MVC does for you replaces all special characters like "'<> (and a few more) with their corresponding HTML codes, such &#39;&quot;&lt;&gt;.

Say you have an object Customer, and you are trying to put it in a <script> section like this:

  <script>
    var customers = JSON.parse('@JsonSerializer.Serialize(Model.Customer)');
  </script>

then all you are going to end up in the browser is going to look something like this:

  <script>
    var customers = JSON.parse('{&quot;Id&quot;:1,&quot;FirstName&quot;:&quot;Hasim&quot;,&quot;LastName&quot;:&quot;Santello&quot;,&quot;DOB&quot;:&quot;2/09/2004&quot;}');
  </script>

and it’s not even a correct JSON! ASP.NET MVC made it safe for you, but also, unfortunately, also broke it.

@Html.Raw to the rescue

To turn all those &quot; and such into proper Javascript, you need to tell ASP.NET to skip the encoding and output the raw data:

  <script>
    // ...
    var customers = JSON.parse('@Html.Raw(JsonSerializer.Serialize(Model.Customers))');
    // ...
  </script>

…and viola! it results in a nice, clean, parsable JSON:

  <script>
    // ...
    var customers = JSON.parse('{"Id":1,"FirstName":"Hasim","LastName":"Santello","DOB":"2/09/2004"}');
    // ...
  </script>

Passing the data from Controller to View

In this instance, I strongly recommend avoid using TempDataSessionViewData or ViewBag and just pass the data you need in the view as part of the controller’s model. There are multiple reasons why you shouldn’t be using the methods listed above, but the main is to keep things simple and strongly-typed. So in your controller return the view in the following manner:

  public IActionResult YourControllerMethod()
  {
      var model = new YourModelClass
      {
        // Set whichever fields in here
      };
      return View(model);
  }

…and in your view, at the top of the page, declare the model class, so that you can have compile-time checking and code completion:

  @model YourModelClass
  <!-- rest of your View.cshtml -->

A word of warning about XSS

As mentioned previously, check out that XSS article, and also be mindful of how you use the data received from the server, whether that’s embedded in the page with @Html.Raw or via Ajax.

For instance, do not concatenate strings to make HTML entities. This example

  <script>
    // ...
    var customer = JSON.parse('... some malicious JSON here with XSS attack...');
    $(body).append($('<div>' + customer.Name + '</div>');
    // ...
  </script>

will introduce a very obvious XSS security hole in your site, because if a malicious user updates their name to <script>alerts('YOU PWND!');</script> that code will execute on clients’ browsers.

Whichever JavaScript framework you’re using, check its documentation on how to avoid XSS. With jQuery, use methods like .text() to set text of newly created elements.

Open Source Licenses

Apache License 2.0: The Basics

Open source licenses come in two flavors: permissive and copyleft. The Apache License 2.0 is in the permissive category, meaning that users can do (nearly) anything they want with the code, with very few exceptions.

However, unlike that of the MIT license, the text of the Apache License 2.0 is quite dense and difficult to read. You can read it here, but be warned — it’s fairly heavy on the legal terminology. Below, we’ll break it down into more digestible language.

Read more here

Philips Hue vs Kasa

Are you looking to build a smart home. Should you go with KASA Blubs or Hue? Read below;

I’d still go Hue if I had to choose one or the other.

Not only is router congestion a possible issue but coverage is usually a much bigger issue. Most people have terrible Wi-Fi coverage. The Wi-Fi chip in the bulbs usually is fairly low power so while it may be able to hear the command signal, it may not be able to send the return signal acknowledging. This can lead to some frustrating troubleshooting when the Wi-Fi checked using a phone with a much stronger Wi-Fi chip. Zigbee on the other hand, is a mesh network that can make strong coverage easier to manage because each bulb is a repeater.

Hue also has an advantage on integrations. There are more Hue integrations in other ecosystems than Kasa by a wide margin. This is great if you’re not using something like r/homeassistant or Alexa as a hub.

Hue has brighter bulbs. Hue’s new ones go up to 1600 lumens where Kasa is still at 800 lumens last time I looked. Yes, the difference is noticeable even with multiple 800 ln lamps vs 1 1600 ln lamp.

Controlling the bulbs from the wall is easier with Hue. It can be done with Kasa but Hue’s dimmer switches are so much easier to setup. It took about a month for me to fed up with only being able to turn on/off my lights with my phone to get some Hue dimmers for my wall. There are light switch replacements that can work with Wi-Fi bulbs but they tend to be expensive and usually require a hub anyway. The majority of them are designed with Hue and Zigbee in mind.

If none of those bother you, then it doesn’t really matter which system you choose. If you do choose Hue, to make the prices more palatable, it’s better to buy them over time as the go on sale or used bulbs. It took ~6 years for me to switch out ~50 bulbs for Hues on my limited budge.

That all being said, I still like my Kasa smart plugs over the Hue ones, mostly because of energy monitoring options from Kasa. I run Home Assistant so crossing ecosystems isn’t a big deal for me.

What I like best about hue is the open API, I hate that Kasa’s API is available but not open/supported/published by TP Link and they keep threatening to take it away. What I hate most about hue is the expense.

Hue has motion detector gadget, which would turn on the bulbs when movement is detected and shut them off because motion is no more sensed.

Hue bridge uses Zigbee. Zigbee creates a mesh network, and so each lightbulb may function as a repeater, discreetly passing messages through to the other in sequence.

This allows the user to take Hue much farther than your router might normally allow, creating it much more practical to get initiated with Philips’ wide range, including its huge diversity of inside lighting systems.

Philips Hue Home & Away function is extremely effective if you enjoy living alone.

References

https://www.philips-hue.com/en-us

https://www.kasasmart.com/us

Computer Graphic Cards

DirectX 12 Ultimate is the new gold standard for gaming graphics on both PC and the next generation of Xbox consoles:

DirectX is a technical tool that helps game developers interact with sound and graphics cards. Although it can be installed on any computer, most users won’t ever need it. It runs when you play a game made with DirectX and that’s it. You’re only going to need to get to know it better if you want to program with it yourself. It has one of the most agile runtime processes amongst this category.

Reference 

https://devblogs.microsoft.com/directx/directx-12-ultimate-for-holiday-2020/