gpt4 book ai didi

c# - 从 MVC Controller 获取 JSON 对象

转载 作者:搜寻专家 更新时间:2023-11-01 04:08:54 25 4
gpt4 key购买 nike

我想要的是在对跨域进行 Ajax 调用时保护我的开发人员 key 。在我直接访问 url 并插入我的 key 之前。像这样

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

这会给我以下对象,我可以很容易地解析它。

enter image description here

但是,如前所述,任何人都可以在此过程中轻松获取我的 key 。所以我决定将此操作移至我的 Controller (是的,我知道这里不应该有业务逻辑,但它更安全,而且这是一个快速的过程)。

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

Javascript

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

我的 Controller 接受它并尝试返回 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 });
}

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

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

enter image description here

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

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

但是返回的只是一些空对象。

enter image description here

在过去的 4 个小时里,我一直在反复试验、搜索和猜测。我不知道该尝试什么了。我只希望我的 Controller 传回一个可以像这样再次读取的对象。 (或者至少是某种格式化的 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) {}
});

最佳答案

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

示例

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

return Json(text, JsonRequestBehavior.AllowGet);
}

关于c# - 从 MVC Controller 获取 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25142325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com