.NET Core 3.1 中的 "Pass through" 控制器操作(获取和 returns JSON)
"Pass through" controller action (gets and returns JSON) in .NET Core 3.1
以前可能有人这样做过,但我似乎无法正确地提出问题来找到结果。我想从视图中进行 AJAX 调用,但我不能直接从 javascript 调用外部 API,因为有一个我无法公开的密钥。我的想法是让我从调用实际外部 REST API 的页面调用另一个控制器操作,我想从中获取数据并将其作为 JSON 传递。我看到很多通过 C# 获取 JSON 并将其反序列化的示例,但在您获取 JSON 然后 return 并从视图中使用它的地方并不多。任何帮助表示赞赏。
public JsonResult GetStuff()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("Stuff/?Id=" + id).Result;
*code to take response and pass it on as a JSON that I can consume from Javascript
}
这是我推荐的。
[HttpGet("myapi/{id}");
public async Task MyApi(int id) {
// Replace these lines as needed to make your API call properly.
using HttpClient client = new() {
BaseAddress = REMOTE_SERVER_BASE
}
// Make sure to properly encode url parameters if needed
using HttpResponseMessage response = await client.GetAsync($"myapi/{id}");
this.HttpContext.Response.StatusCode = (int)response.StatusCode;
foreach (KeyValuePair<string, IEnumerable<string>> header in response.Headers) {
this.HttpContext.Response.Headers[header.Key] = new StringValues(header.Value.ToArray());
}
await response.Content.CopyToAsync(this.HttpContext.Response.Body);
}
这会将所有常见的响应字段(例如状态代码、headers 和 body 内容)复制到您的响应中。
此代码未经测试,因此您可能需要稍微调整一下,但它应该足以让您入门。
以前可能有人这样做过,但我似乎无法正确地提出问题来找到结果。我想从视图中进行 AJAX 调用,但我不能直接从 javascript 调用外部 API,因为有一个我无法公开的密钥。我的想法是让我从调用实际外部 REST API 的页面调用另一个控制器操作,我想从中获取数据并将其作为 JSON 传递。我看到很多通过 C# 获取 JSON 并将其反序列化的示例,但在您获取 JSON 然后 return 并从视图中使用它的地方并不多。任何帮助表示赞赏。
public JsonResult GetStuff()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("Stuff/?Id=" + id).Result;
*code to take response and pass it on as a JSON that I can consume from Javascript
}
这是我推荐的。
[HttpGet("myapi/{id}");
public async Task MyApi(int id) {
// Replace these lines as needed to make your API call properly.
using HttpClient client = new() {
BaseAddress = REMOTE_SERVER_BASE
}
// Make sure to properly encode url parameters if needed
using HttpResponseMessage response = await client.GetAsync($"myapi/{id}");
this.HttpContext.Response.StatusCode = (int)response.StatusCode;
foreach (KeyValuePair<string, IEnumerable<string>> header in response.Headers) {
this.HttpContext.Response.Headers[header.Key] = new StringValues(header.Value.ToArray());
}
await response.Content.CopyToAsync(this.HttpContext.Response.Body);
}
这会将所有常见的响应字段(例如状态代码、headers 和 body 内容)复制到您的响应中。
此代码未经测试,因此您可能需要稍微调整一下,但它应该足以让您入门。