Add unparsable cruft to ASP.NET MVC JsonResult - javascript

In light of posts such as these:
JSON unparseable cruft: Why so serious?
Why do people put code like "throw 1; <dont be evil>" and "for(;;);" in front of json responses?
Why does Google prepend while(1); to their JSON responses?
I would like to follow the advice laid out in the following answer: How should web app developers defend against JSON hijacking?
Is there an easy way to add an unparsable cruft to JSON responses built using System.Web.Mvc.JsonResult? The security.se post suggests that I use </* at the beginning of the response.

You could write a custom action result to perform this:
public class SafeJsonResult: JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write("</*");
base.ExecuteResult(context);
}
}
and then use it instead of the default one:
public ActionResult Index()
{
return new SafeJsonResult
{
Data = new { Foo = "bar" },
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
};
}

Related

how to return js object to unity

I'm using the Google Draco decoder to decode mesh the following.
var dracoGeometry;
dracoGeometry = new decoderModule.Mesh();
decodingStatus = decoder.DecodeBufferToMesh(buffer, dracoGeometry);
when I check the type of the draceGeometrytry:
console.log( typeof dracoGeometry);
I get the
"object" type.
Now my problem is "how can I return this object to unity". What return type supported in C# to accept js object?
You can send strings or numbers, so what I would do is create a js object that has the data you need then call JSON.stringify on it to convert it to a string then send that over using unityInstance.SendMessage:
function sendToUnity(obj) {
unityInstance.SendMessage('MyGameObject', 'MyMethod', JSON.stringify(obj));
}
// in a script attached to a gameobject named "MyGameObject"
void MyMethod(string s)
{
Debug.Log(s);
// decode from json, do stuff with result etc
}
As for what you can do with that data while it is in JSON string form, you can use a variety of solutions to decode the JSON string once you have it in Unity. See Serialize and Deserialize Json and Json Array in Unity for more information.
So if your js looks like this:
function sendToUnity(obj) {
unityInstance.SendMessage('MyGameObject', 'MyMethod', JSON.stringify(obj));
}
sendToUnity({
playerId: "8484239823",
playerLoc: "Powai",
playerNick:"Random Nick"
});
You could do something like this in Unity:
[Serializable]
public class Player
{
public string playerId;
public string playerLoc;
public string playerNick;
}
...
void MyMethod(string s)
{
Player player = JsonUtility.FromJson<Player>(s);
Debug.Log(player.playerLoc);
}
Source: Programmer's answer
There are some methods available, but it doesn't seem possible at the moment to send a mesh from js to unity. If you are working with google draco, I recommend you to follow this fork

JQuery Javascript function to return highchart graph data source in JSON and formatted correctly through Selenium and C#

I am trying to figure out how to get the JSON equivalent of a highchart graph returned to me using Selenium and C#. I got pretty far, but I am hitting a couple issues. For the specific highchart, perform the following steps:
Go here https://rcpsc.releasecandidate-community360qa.net/login.aspx?action=enablelogin
Login with: uw_lr1/test
The chart will show on the next page once you login. The ID of the chart element is "EPAChart"
Issue #1
I can use the below function in the Console tab of DEV tools to retrieve the data in JSON format, but it does not organize it correctly (it lists all EPA's first, then all values of those EPAs second) JSON.stringify(angular.element($('#EPAChart')).scope().$parent.vm['epaGraphData']);
When I plug this into Visual Studio with C# and Selenium and then try to convert this to a DataTable, it does not allow me because the data is not organized correctly. For a similar issue, see : Newtonsoft.Json JsonConvert To Datatable
using Newtonsoft.Json;
using OpenQA.Selenium;
string jsText = string.Format("return JSON.stringify(angular.element($('#EPAChart')).scope().$parent.vm['epaGraphData']);")
var jsResult = driver.ExecuteScript(jsText) as string;
JsonConvert.DeserializeObject<DataTable>(jsResult);
Issue #2
I have a Javascript/Jquery function which produces the JSON organized correctly, but I dont know how to call it using Selenium/C#. The code, driver.ExecuteScript, does not like this function, I guess because it is too complicated and uses variables, so driver.ExecuteScript (IJavaScriptExecutor->ExecuteScript) throws an exception. Here is the function:
var epadatasource = []; for(var i=0;i<angular.element($('#EPAChart')).scope().$parent.vm['epaGraphData'].Categories.length;i++){epadatasource.push({category: angular.element($('#EPAChart')).scope().$parent.vm['epaGraphData'].Categories[i], data: angular.element($('#EPAChart')).scope().$parent.vm['epaGraphData'].Data[i]}); }; JSON.stringify(epadatasource);
For Issue #2, how do I call the above function in C#/Selenium so that it doesnt throw an exception and instead returns my JSON? Or for issue #1, is there a workaround to organize that JSON correctly?
I figured out a workaround for issue #1 and #jeffC provdided the solution to issue #2
Issue 1 resolution is to add JSON to C# object, then convert it to a new object, and deserialize it for a fixed JSON:
public static string TransformJSON(string json, IWebElement chartElem)
{
string fixedJson = "";
if (chartElem.GetAttribute("id") == "EPAChart")
{
dynamic obj = JsonConvert.DeserializeObject<EPAObservationCountOriginal>(json);
List<EPAObservationCountFixed> fixedObject = new List<EPAObservationCountFixed>();
for (int i = 0; i < obj.Categories.Length; i++)
{
fixedObject.Add(new EPAObservationCountFixed() { category = obj.Categories[i], data = obj.Data[i] });
}
fixedJson = JsonConvert.SerializeObject(fixedObject);
}
return fixedJson;
}
#endregion methods
#region Class objects representing graphs
public class EPAObservationCountFixed
{
public string category { get; set; }
public string data { get; set; }
}
public class EPAObservationCountOriginal
{
public string[] Categories { get; set; }
public string[] Data { get; set; }
}
Issue 2 resolution is to add the word "return" in the function:
var epadatasource = []; for(var i=0;i<angular.element($('#EPAChart')).scope().$parent.vm['epaGraphData'].Categories.length;i++){epadatasource.push({category: angular.element($('#EPAChart')).scope().$parent.vm['epaGraphData'].Categories[i], data: angular.element($('#EPAChart')).scope().$parent.vm['epaGraphData'].Data[i]}); }; return JSON.stringify(epadatasource);

ASP MVC send an Array object to a JavaScript function

I am using ASP MVC for my university coursework. However I have encountered a problem, before I was sending too many AJAX requests which was causing my page to take way too long to load. Therefore I thought I could improve the situation by sending the arrays from the database to the view and then put them into my jquery function inline.
So here is how it looks I have my simple model:
public class NewBooking
{
public IEnumerable<dynamic> parks { get; set; }
}
Then in my controller I set the parks with information from the database as you can see here:
public ActionResult Index()
{
var model = new NewBooking();
var parks = Database.Open("SQLServerConnectionString").Query("SELECT * FROM Park");
var output = from o in parks
select new { parkID = o.parkID, parkName = o.parkName };
model.parks = output.ToList();
return View(model);
}
Now, this returns to the view all the information I am expecting, as you can see below if I simply called the model parks in the view:
#model build_01.Models.Timetabler.NewBooking
#{
#Model.parks
}
I know this method wouldn't however with a for loop it works fine, now to my issue; I'm trying to call a JavaScript function and pass this array to it.
$(document.ready(function () {
slotAvailability(#Model.parks);
}));
Is there something I can do to this #Model.parks to be able to send it to the function? Kind of like how I would do JSON if I was using AJAX.
As it stands trying to call it like this gives me this error in my console:
Uncaught SyntaxError: Unexpected number
I can see why, if I was to inspect element I can see that the function parse looks like this:
slotAvailability(System.Collections.Generic.List`1[<>f__AnonymousType3`2[System.Object,System.Object]]);
Thanks
You should use the Json.Encode function. Also make sure tha you close your parenthesis at the proper place, after document:
$(document).ready(function () {
var parks = #Html.Raw(Json.Encode(Model.parks));
slotAvailability(parks);
});
Also using dynamic seems like a bad design here. You don't get any Intellisense. You'd rather have a view model:
public class ParkViewModel
{
public int ParkId { get; set; }
public int ParkName { get; set; }
}
and then your NewBooking model:
public class NewBooking
{
public IEnumerable<ParkViewModel> Parks { get; set; }
}

Bind array of complex objects in GET request - jquery.param() traditional flag

I'm trying make a jquery.ajax call to the following controller action:
public ActionResult Handler(SemanticPart[] semanticParts, string first, string last)
I have the following data JSON object with the corresponding server side model having public { get; set; } properties:
var data = {
semanticParts: [{ hasLabel: "label", hasType: "type", hasIndex : 0 }],
first: "first",
last : "last"
};
The problem is jQuery.param seems to have no serialization option for the default MVC model binder.
decodeURIComponent($.param(data)) produces:
"semanticParts[0][hasLabel]=label&semanticParts[0][hasType]=type&semanticParts[0][hasIndex]=0&first=first&last=last"
while setting the traditional flag like so decodeURIComponent($.param(data, true)) produces:
"semanticParts=[object+Object]&first=first&last=last"
MVC's default model binder for complex arrays needs the following to bind correctly (tested in Fiddler Composer):
"semanticParts[0].hasLabel=label&semanticParts[0].hasType=type&semanticParts[0].hasIndex=0&first=first&last=last"
Which simply used: array[0].property= instead of array[0][property]=
I understand there's no universal specification for param strings agreed-upon by all web frameworks but why jQuery.param with traditional flag set true returns a [object+Object] is beyond me... that is absolutely useless in any framework.
It there any way to patch this?
Perhaps a regex to replace the pattern [#][text] with [#].text? (actually the encoded version of this is more relevant)
You should implement a model to hold this parameters:
public class SemanticPartViewModel
{
public List<SemanticPart> semanticParts { get; set;}
public string first { get; set; }
public string last { get; set;}
}
And change the controller to receive this as parameter
public ActionResult Handler(SemanticPartViewModel semanticParts)
{
/*Do stuff*/
}
You should use JSON.stringify(mydata) as well to create the data for the $.ajax call
This way the default modelbinder will take care about the rest.

Error using dynamic keyword in asp.net mvc 4

I am getting this long error when i accpet the parameter as dynamic on my server side action method in mvc 4.
{"Message":"An error has
occurred.","ExceptionMessage":"'Newtonsoft.Json.Linq.JObject' does not
contain a definition for
'TournamentId'","ExceptionType":"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException","StackTrace":"
at CallSite.Target(Closure , CallSite , Object )\r\n at
System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite
site, T0 arg0)\r\n at
ManagerDeTorneos.Web.Controllers.TournamentDateController.Create(Object
data) in
F:\Prince\Projects\Juan\trunk\ManagerDeTorneos.Web\Controllers\TournamentDateController.cs:line
133\r\n at lambda_method(Closure , Object , Object[] )\r\n at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c_DisplayClass13.b_c(Object
instance, Object[] methodParameters)\r\n at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object
instance, Object[] arguments)\r\n at
System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1
func, CancellationToken cancellationToken)"}
[HttpPost]
public HttpResponseMessage AddMatch(dynamic data)
{
int tournamentDateId = (int)data.TournamentDateId.Value;
var tournamentDate = Catalog.TournamentDateRepository.GetById(tournamentDateId);
if (tournamentDate == null)
{
throw ExceptionHelper.NotFound("Fecha no encontrada!");
}
In The above method data Contains tournamentId as sent from ajax call as JSON.Stringify({'TournamentId':'5'}).
Can anybody tell me what is the cause of error. I even replaced the dll of Newtonsoft.Json as well
You are right dan but i fixed my issue by removing that dll from GAC. May be in GAC it was using old assembly
The error is caused by the fact that you typed your parameter as dynamic, which means that the model binder doesn't know what to make it. It's the same as if you were to declare it as an object. Since you are providing JSON, it serializes the object as a Json.Net JObject. Just because you define it as a dynamic doesn't mean that it's going to magically take whatever shape you need it to.
Change it to a concrete type - something that matches the structure of the provided JSON:
public class TournamentInfo
{
public int TournamentId { get; set; }
}
[HttpPost]
public HttpResponseMessage AddMatch(TournamentInfo data)
{
int tournamentDateId = data.TournamentId;
var tournamentDate = Catalog.TournamentDateRepository.GetById(tournamentDateId);
if (tournamentDate == null)
{
throw ExceptionHelper.NotFound("Fecha no encontrada!");
}
This way, the binder knows what it's supposed to turn the JSON into, and since TournamentInfo matches the structure of the JSON, it won't have any trouble serializing it.
Don't misuse dynamic. It was not introduced into C# so developers could stop defining classes.

Categories

Resources