简体   繁体   中英

Retrieving the response from Rest API

I am working on creating an API that call the other third party API. The third party API is an REST API and returns response in the JSON format when I call it in the web browser

[{"Acc":"IT","Cnt":"023","Year":"16"}]

I am trying to get the same response when I call the third party API from my API.

public IHttpActionResult Get(string acctID) 
{
    using (var client_EndPoint= new HttpClient())
    {
        Uri uri_EndPoint = new Uri(BaseURL_EndPoint);
        client_EndPoint.BaseAddress = uri;
        client_EndPoint.DefaultRequestHeaders.Accept.Clear();
        client_EndPoint.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        string EndPoint_URL = BaseURL_EndPoint+"api/NameCreation?Account="+acctID;
        var response_EndPoint = client_EndPoint.GetAsync(EndPoint_URL).Result;
        string responseString = response_EndPoint.Content.ReadAsStringAsync().Result;
        return Ok(responseString);
    }
}

What I have been doing is getting the response from the third party API in a string. But I am checking if there is a way I can get in the JSON format so I can return them directly. The return type of the get method is IHttpActionResult . If I am returning as string the response looks like

"[{\"Acc\":\"adm\",\"Cnt\":\"001\",\"Year\":\"16\"}]"

Any help is greatly appreciated.

Create a model to hold rest api data

public class Model {
    public string Acc { get; set; }
    public string Cnt { get; set; }
    public string Year { get; set; }
}

Deserialize it from api

var response_EndPoint = await client_EndPoint.GetAsync(EndPoint_URL);
var models = await response_EndPoint.Content.ReadAsAsync<Model[]>();

And then return that

return Ok(models);

Full example

public async Task<IHttpActionResult> Get(string LabName) {

    using (var client_EndPoint = new HttpClient()) {

        //...other code removed for brevity

        var response_EndPoint = await client_EndPoint.GetAsync(EndPoint_URL);
        var models = await response_EndPoint.Content.ReadAsAsync<Model[]>();
        return Ok(models);
    }
}

you can use Newtonsoft.Json ,Just add it from nuget and add this config to webapiconfig:

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =     
Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

then use

return Json(responseString)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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