Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonResult with Base64 encoding

I use Json(object) to return JsonResult in ASP.Net MVC.

One of the properties in the object is a string that must be Base64 encoded.

public class MyClass
{
   public string BlockOfText = "Hello World";
}

Should be converted to the following Json result

{
     "BlockOfText" : "SGVsbG8gV29ybGQ="
}

How can I tell Json Serializer to encode the property to Base64?

like image 679
Gautam Jain Avatar asked Apr 20 '26 10:04

Gautam Jain


1 Answers

One solution is to encode your string server based. Before serializing your object just do a :

var instance.BlockOfText64Base = System.Convert.ToBase64String(Encoding.Default.GetBytes(instance.BlockOfText));
return Json(instance, JsonRequestBehavior.AllowGet);

Hope it helps.

like image 97
alexl Avatar answered Apr 23 '26 03:04

alexl