When we use Mvc controllers as REST API Services, usually we may need to return data as JSON.
If we return data as its in ASP.NET Controllers, the data will be converted to String using ToString()
public string[] MyJsonData()
{ return new String[] { "A", "B", "C" };
}
will return
System.String[]
To avoid this we can use JsonResult method in Controller class
public JsonResult MyJsonData()
{ return Json(new String[] { "A", "B", "C" });
}
If we use the above code when we need to GET the data, it may throw the below error.
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet
To avoid this we can pass a second parameter to the Json method as
public JsonResult MyJsonData()
{ return Json(new String[] { "A", "B", "C" }, JsonRequestBehavior.AllowGet);
}
No comments:
Post a Comment