从MVC控制器获取JSON对象

时间:2022-07-19 21:06:32

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调用时保护我的开发人员密钥。在我直接进入网址并插入我的密钥之前。喜欢这个

$.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.

这将给我以下对象,我可以轻松解析。

从MVC控制器获取JSON对象

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).

但是,如上所述,任何人都可以在此过程中轻松抓住我的钥匙。所以我决定将这个动作移动到我的Controller(是的,我知道这里不应该有业务逻辑,但它更安全,这是一个快速的过程)。

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

所以我现在正在做的是运行我的Javascript,它调用Controller以获得Json返回。

Javascript

使用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.

我的控制器接受了这个并尝试返回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.

但是在此过程中,我返回的字符串不是JSON对象,因此我的脚本无法对其进行解析。

It returns the entire json as one long string.

它将整个json作为一个长字符串返回。

从MVC控制器获取JSON对象

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

此时我尝试将以下内容添加到Controller中。

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

But all that returned was some empty Object.

但所有返回的都是一些空的Object。

从MVC控制器获取JSON对象

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)

在过去的4个小时里,我一直在试错,搜索和猜测。我不知道该怎么办了。我只是希望我的Controller传回一个可以再次读取的Object。 (或至少某种格式化的json对象)

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

5 个解决方案

#1


3  

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.

您的方法似乎不需要是POST,因为它只是获取数据而不是修改数据。因此,您可以将其设置为GET。

Example

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

    return Json(text, JsonRequestBehavior.AllowGet); 
}

#2


1  

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.

根据您收到的回复,我可以理解文本已经包含您想要的JSON。

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

现在替换return Json(new {json = text});与Json(文本);那应该解决它。

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

#3


0  

I think the problem lies where you say return Json(new {json = text;}). That's telling the json serializer to dump all your data into a property in the json obect called 'json', which is what you're seeing in the response.

我认为问题在于你说返回Json(new {json = text;})。这告诉json序列化程序将所有数据转储到名为'json'的json对象中的属性中,这就是您在响应中看到的内容。

Try return Json(text) instead.

尝试返回Json(文本)。

#4


0  

Ending up using WebClient

使用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
        }
    });

#5


0  

I was having the same issue as the original poster: the ReadToEnd() call result escapes special characters and thus doesn't look like JSON to the receiving end, but then I saw a similar question answered here and thought others reading this might find it helpful as well.

我遇到了与原始海报相同的问题:ReadToEnd()调用结果转义特殊字符,因此看起来不像接收端的JSON,但后来我看到一个类似的问题在这里得到解答,并认为其他读这个可能会找到它也很有帮助。

To summarize: Deserializing in the Controller which the original poster tried was key, but also as others have pointed out, the return doesn't need the new {} call.

总结一下:在原始海报尝试的控制器中反序列化是关键,但正如其他人所指出的那样,返回不需要新的{}调用。

So pieced together:

所以拼凑在一起:

using (var sr = new StreamReader(endpointResponse.GetResponseStream())) {
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
    return Json(jsonObject, JsonRequestBehavior.AllowGet);
}

#1


3  

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.

您的方法似乎不需要是POST,因为它只是获取数据而不是修改数据。因此,您可以将其设置为GET。

Example

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

    return Json(text, JsonRequestBehavior.AllowGet); 
}

#2


1  

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.

根据您收到的回复,我可以理解文本已经包含您想要的JSON。

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

现在替换return Json(new {json = text});与Json(文本);那应该解决它。

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

#3


0  

I think the problem lies where you say return Json(new {json = text;}). That's telling the json serializer to dump all your data into a property in the json obect called 'json', which is what you're seeing in the response.

我认为问题在于你说返回Json(new {json = text;})。这告诉json序列化程序将所有数据转储到名为'json'的json对象中的属性中,这就是您在响应中看到的内容。

Try return Json(text) instead.

尝试返回Json(文本)。

#4


0  

Ending up using WebClient

使用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
        }
    });

#5


0  

I was having the same issue as the original poster: the ReadToEnd() call result escapes special characters and thus doesn't look like JSON to the receiving end, but then I saw a similar question answered here and thought others reading this might find it helpful as well.

我遇到了与原始海报相同的问题:ReadToEnd()调用结果转义特殊字符,因此看起来不像接收端的JSON,但后来我看到一个类似的问题在这里得到解答,并认为其他读这个可能会找到它也很有帮助。

To summarize: Deserializing in the Controller which the original poster tried was key, but also as others have pointed out, the return doesn't need the new {} call.

总结一下:在原始海报尝试的控制器中反序列化是关键,但正如其他人所指出的那样,返回不需要新的{}调用。

So pieced together:

所以拼凑在一起:

using (var sr = new StreamReader(endpointResponse.GetResponseStream())) {
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
    return Json(jsonObject, JsonRequestBehavior.AllowGet);
}