I've set up an Actionresult in an MVC controller that will be invoked when a URL is visited (routeconfig) and allow a request to be made from a dialogflow JSON request, and the JSON from this will then be parsed and actioned on our end of things / return appropriate JSON. When i try doing this using streamreader ReadToEndAsync, this doesn't work and JObject.Parse fails/errors.
I've tried different ways of trying to parse the JSON, with continuewith etc, but these don't seem to work as expected.
Controller ActionResult
public ActionResult JSONQuery()
{
System.IO.StreamReader reader = new System.IO.StreamReader(System.Web.HttpContext.Current.Request.InputStream);
reader.BaseStream.Position = 0;
var requestFromPost = reader.ReadToEndAsync();
var intentRequestJSON = JObject.Parse(requestFromPost.Result);
//JToken Name = intentRequestJSON.SelectToken("test.name");
return new ContentResult { Content = requestFromPost.Result, ContentType = "application/json" };
}
Test AJAX query to enable me to debug using breakpoint in Visual Studio
$.ajax({
url: 'http://localhost/test/',
type: 'POST',
data: {
json: JSON.stringify({
test: "Testing"
})
},
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Nope");
}
});
What i'd expect is for the JSON to be parsed correctly, so i can do logic on the key/value pairs. What i'm currently getting is:
Newtonsoft.Json.JsonReaderException HResult=0x80131500 Message=Unexpected character encountered while parsing value: j. Path '', line 0, position 0. Source=Newtonsoft.Json StackTrace: at Newtonsoft.Json.JsonTextReader.ParseValue() at Newtonsoft.Json.JsonTextReader.Read() at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader) at Newtonsoft.Json.Linq.JObject.Parse(String json) at TestController.<>c.<DiagflowDivertQuery>b__37_0(Task`1 t) in C:\inetpub\wwwroot\test\Web\Controllers\TestController.cs:line 2988 at System.Threading.Tasks.Task.Execute()
After a bit of reading, the way i found that works (and is simpler) is:
public ActionResult JSONQuery() {
System.IO.StreamReader reader = new System.IO.StreamReader(System.Web.HttpContext.Current.Request.InputStream);
reader.BaseStream.Position = 0;
var requestFromPost = reader.ReadToEndAsync();
dynamic json = JsonConvert.DeserializeObject(requestFromPost.Result);
string intent = json.queryResult.intent.name;
return new ContentResult { Content = requestFromPost.Result, ContentType = "application/json" };
}
Hope this helps someone.
User contributions licensed under CC BY-SA 3.0