Austin Austin - 3 months ago 13
Ajax Question

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) {}
});

Answer

Ending up using WebClient

[HttpPost]
        public ActionResult teamLookUp(string ID)
        {
            string text = "";
            try
            {
                using (var webClient = new System.Net.WebClient())
                {
                    webClient.Encoding = Encoding.UTF8;
                    var json2 = webClient.DownloadString("https://na.api.pvp.net/api/lol/na/v2.3/team/" + ID + "?api_key=myKey");
                    return Json(json2);
                }
            }
            catch (Exception e)
            {
                text = "error";
            }
            return Json(new { json = text });
        }

And I parsed it like normal,

    $.ajax({
        url: "/Competitive/teamLookUp",
        type: "POST",
        data: "ID=" + ID,
        dataType: "json", 
        success: function (resp) {
            if (resp["json"] == "error") {
                // error reaching server
            } else {
                // successfully reached server
            }                
            json = JSON && JSON.parse(resp) || $.parseJSON(resp);

            var userID = ID;
            teamName = json[userID].name;
            teamID = json[userID].fullId;
            teamCPT = json[userID].roster.ownerId;
            teamTag = json[userID].tag;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
             // error
        }
    });