首页 > 解决方案 > 如何使用 API 并以 JSON 格式返回内容?

问题描述

我正在努力解决以下问题:

我创建了一个包含以下项目的解决方案:1 个 MVC 前端和 2 个测试 API,用于测试我的后端 API 代理。

在我的前端,我调用我的 API 代理(它也是一个 API),它将请求发送到我的 2 个测试 API。我在我的 API 代理中以字符串格式接收此请求的响应,我试图将其返回到 JSON 到我的前端,我如何使用这个 api 并将 JSON 中的响应返回到我的前端?看下面的代码:

前端调用我的 API 代理:

[HttpGet]
    public async Task<ActionResult> getCall()
    {
        string url = "http://localhost:54857/";
        string operation = "getClients";

        using (var client = new HttpClient())
        {
            //get logged in userID
            HttpContext context = System.Web.HttpContext.Current;
            string sessionID = context.Session["userID"].ToString();

            //Create request and add headers
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Custom header
            client.DefaultRequestHeaders.Add("loggedInUser", sessionID);

            //Response
            HttpResponseMessage response = await client.GetAsync(operation);
            if (response.IsSuccessStatusCode)
            {
                string jsondata = await response.Content.ReadAsStringAsync();
                return Content(jsondata, "application/json");
            }
            return Json(1, JsonRequestBehavior.AllowGet);
        }
    }

我的 API 代理使用我的两个测试 API 之一:

    [System.Web.Http.AcceptVerbs("GET")]
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("RedirectApi")]
    public void getCall()
    {
        setVariables();

        WebRequest request = WebRequest.Create(apiUrl);
        HttpWebResponse response = null;
        response = (HttpWebResponse)request.GetResponse();

        using (Stream stream = response.GetResponseStream())
        {
            StreamReader sr = new StreamReader(stream);
            var srResult = sr.ReadToEnd();
            sr.Close();
            //Return JSON object here!

        }
    }

我也担心我的前端期望的是 ActionResult 而不是 JSON 对象,希望您能在这里找到一些建议。

提前致谢!

标签: c#asp.netapiasp.net-mvc-4actionresult

解决方案


使用 HttpClient 发出请求,允许您将内容读取为字符串。您的 API 需要进行配置,以便它允许 JSON 响应(默认行为),然后这是一个发出请求并将其读取为 JSON 格式的字符串的示例(如果 API 返回 JSON 正文)。

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();

从 HTTP 请求接收 JSON 数据


推荐阅读