Home > Software design >  Fetch data in a POST Request in asp.net core
Fetch data in a POST Request in asp.net core

Time:03-23

I am using an external web link to get data and fetch it to json The reason why I need to handle it by the controller is to filter the data of it. Sadly, an api link was programmatically incorrect because instead of requesting it as GET method, it was programmed as POST method. I had this code simple code below but the return was a header data not the actual data of the api.

[HttpPost, Route("get/subproject")]

        public ActionResult subproject()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(@"https://thisisjustasample.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                

                HttpResponseMessage hrm = client.PostAsync("/api/new/get/subproject/details/get_dto", null).Result;
                
                
                    return Ok(hrm);
                
                
            }
        }

The output of the code above is this.

    {
        "version": "1.1",
        "content": {
            "headers": [
                {
                    "key": "Content-Length",
                    "value": [
                        "29942142"
                    ]
            

    },
            {
                "key": "Content-Type",
                "value": [
                    "application/json; charset=utf-8"
                ]
            },
            {
                "key": "Expires",
                "value": [
                    "-1"
                ]
            }
        ]
    }
}

What I need is this data below.

{
    "sub_project_id": 267892,
    "engineeringMigrationId": 0,
    "modality_id": 21,
    "id": null,
    "reportID": null,
    "month": null,
    "year": null,
    "cycle_id": 204
}

Any help would be appreciated. Thanks in advance.

CodePudding user response:

Don't return hrm directly, If you want to get the response data, you need return.

hrm.Content.ReadAsStringAsync().Result

Demo

1.return Ok(hrm);

enter image description here

2.return Ok(hrm.Content.ReadAsStringAsync().Result);

enter image description here

  • Related