Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting JSON Object from MVC Controller

What I want is to protect my developer key while making an Ajax call to a cross-domain. Before I would just go straight to the url and plug in my key. Like this

$.ajax({
    url: "https://na.api.pvp.net/api/lol/na/v2.3/team/TEAM-ID?api_key=mykey",
    type: "GET",
    data: {},
    success: function (json) {
        console.log(json);
            console.log(json[teamID].name);
            console.log(json[teamID].fullId);
            console.log(json[teamID].roster.ownerId);
            console.log(json[teamID].tag);
    },
    error: function (error) {}
});

This would give me the following Object, which I could easily parse out.

enter image description here

However, as mentioned, any person could easily grab my key during this process. So I decided to move this action to my Controller (yes I know there shouldn't be business logic here, but it is more secure and this is a quick process).

So what I am doing now is running my Javascript, which calls the Controller for a Json return.

Javascript

$.ajax({
        url: "/Competitive/teamLookUp",
        type: "POST",
        data: "ID=" + teamID,
        success: function (json) {
            console.log(json);
        }, 
        error: function(error) {
        }
   });

And my Controller takes that in and attempts to return the JSON.

[HttpPost]
public ActionResult teamLookUp(string ID)
{
    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://na.api.pvp.net/api/lol/na/v2.3/team/" + ID + "?api_key=myKey");
    myReq.ContentType = "application/json";
    var response = (HttpWebResponse)myReq.GetResponse();
    string text;

    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        text = sr.ReadToEnd();
    }
    return Json(new { json = text });
}

However during this processs I return a string that is not a JSON object, thus cannot be parsed by my script.

It returns the entire json as one long string.

enter image description here

At this point I tried to add the following to my Controller.

    var json2 = JsonConvert.DeserializeObject(text);
    return Json(new { json = json2 });

But all that returned was some empty Object.

enter image description here

I have been trial and error'ing, searching, and guessing for the past 4 hours. I have no idea what to try anymore. I just want my Controller to pass back an Object that can be readable again like this. (Or at least some sort of formatted json object)

$.ajax({
        url: "/Competitive/teamLookUp",
        type: "POST",
        data: "ID=" + teamID,
        success: function (json) {
            console.log(json);
                console.log(json[teamID].name);
                console.log(json[teamID].fullId);
                console.log(json[teamID].roster.ownerId);
                console.log(json[teamID].tag);
        },
        error: function (error) {}
    });
like image 780
Austin Avatar asked Aug 05 '14 15:08

Austin


People also ask

How pass JSON object in post request in MVC?

Make sure you specify POST type, as ajax method uses GET method by default. MVC Controller: Decorate the Action method with HttpPost verb. This action method will only handle http post request from browser. Ajax submission from the browser will be automatically deserialized to FormData c# class as a poco.

What is return JSON in MVC?

JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Object Notation (JSON) format.

How do I return JSON data in view?

The Controller Action method will be called using jQuery POST function and JSON data will be returned back to the View using JsonResult class object. In this article I will explain with an example, how to use the JsonResult class object for returning JSON data from Controller to View in ASP.Net MVC.


2 Answers

Your method doesn't appear to need to be a POST as it is just getting data rather than modifying it. Therefore you could set it to be a GET instead.

Example

[HttpGet]
public JsonResult teamLookUp(string ID)
{
    // Your code

    return Json(text, JsonRequestBehavior.AllowGet); 
}
like image 172
Colin Bacon Avatar answered Sep 30 '22 17:09

Colin Bacon


Here's an excerpt from your code:

[HttpPost]
public ActionResult teamLookUp(string ID)
{

    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://na.api.pvp.net/api/lol/na/v2.3/team/" + ID + "?api_key=myKey");
    myReq.ContentType = "application/json";


    // here's how to set response content type:
    Response.ContentType = "application/json"; // that's all

    var response = (HttpWebResponse)myReq.GetResponse();
    string text;

    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        text = sr.ReadToEnd();
    }

    return Json(new { json = text }); // HERE'S THE ERRING LINE
}

Based on the response you received, I could understand that text already contains you desired JSON.

Now replace return Json(new { json = text }); with Json(text); and that should fix it.

To answer your question in the comments, here's how you can read the response data:

$.ajax({
    url: "/Competitive/teamLookUp",
    type: "POST",
    data: "ID=" + teamID,
    dataType: "json", // type of data you're expecting from response
    success: function (json) {
        console.log(json);
            console.log(json[teamID].name);
            console.log(json[teamID].fullId);
            console.log(json[teamID].roster.ownerId);
            console.log(json[teamID].tag);
    },
    error: function (error) {}
});
like image 31
Igwe Kalu Avatar answered Sep 30 '22 16:09

Igwe Kalu