繁体   English   中英

.NET Core 3.1 中的“通过”controller 操作(获取并返回 JSON)

[英]“Pass through” controller action (gets and returns JSON) in .NET Core 3.1

以前可能有人这样做过,但我似乎无法正确地提出问题以找到结果。 我想从视图中进行 AJAX 调用,但我不能直接从 javascript 调用外部 API 因为有一个我无法公开的密钥。 My idea is to have another controller action that I call from the page that calls the actual external REST API I want to get data from and just passes it on as a JSON. 我看到很多通过 C# 获得 JSON 并对其进行反序列化的示例,但在获得 JSON 然后从视图中返回并使用它的地方并不多。 任何帮助表示赞赏。

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

这会将所有常见的响应字段(例如状态代码、标头和正文内容)复制到您的响应中。

此代码未经测试,因此您可能需要对其进行一些调整,但它应该足以让您入门。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM