如何使用API 并以JSON格式返回内容?

问题描述 投票:0回答:1

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

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

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

前端调用我的API Broker:

[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 Broker使用了我的两个测试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.net api asp.net-mvc-4 actionresult
1个回答
0
投票

使用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();

Receiving JSON data back from HTTP request

© www.soinside.com 2019 - 2024. All rights reserved.