簡體   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