Where are @Json.Encode or @Json.Decode methods in MVC 6?

What is equivalent of MVC5's @Json.Encode method in MVC6? In MVC5 we can access those methods in views. But I can't find any methods which I can access from MVC 6 views.

I don't want to write a helper method if there is already a built in feature in MVC6.


Solution 1:

After some search, found it:

@inject IJsonHelper Json;
@Json.Serialize(...)

Solution 2:

I've had success with the following:

@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(myObj) as String)

I'm not sure if Json.Encode has made it in yet because it was a part of System.Web which is gone now.

Solution 3:

One of the features of @Json.Encode() was automatic HTML encoding of entities within JSON strings, which is helpful to avoid XSS vulnerabilities. The JsonHelper class is based on Json.NET serialization now, which does support at least some (or all) of this same functionality if configured properly. The other solutions here can be vulnerable to XSS attacks if untrusted data is serialized.

Quick example of a vulnerability:

<script>
    window.something = @Json.Serialize(new { someprop = "Hello</script><script>alert('xss')</script><script>" });
</script>

Will be rendered as

<script>
    window.something = {"someprop":"Hello
</script>
<script>alert('xss')</script>
<script>"};</script>

To properly configure Json.NET to escape HTML entities would be to use the @Json.Serialize(object, serializerSettings) overload and override StringEscapeHandling to EscapeHTML. The settings could be defined in a helper class or injected.

@using Newtonsoft.Json
<script>
    @{
        var settings = new JsonSerializerSettings {StringEscapeHandling = StringEscapeHandling.EscapeHtml};
    }
    window.something = @Json.Serialize(new { someprop = "Hello</script><script>alert('xss')</script><script>" }, settings);
</script>

Which is rendered instead as:

<script>
    window.something = {"someprop":"Hello\u003c/script\u003e\u003cscript\u003ealert(\u0027xss\u0027)\u003c/script\u003e\u003cscript\u003e"};
</script>

Some other methods of safely serializing data to the page in ASP.NET Core can be found here: https://github.com/aspnet/Docs/blob/master/aspnetcore/security/cross-site-scripting.md