'How to create a method that returns the API response
I'm using restsharp as HTTP client, and i don't know how to make possible that API response to return as specific model, or it can be returned as a string or something like that, I know that i'm using async/await, but how can do it correctly for my requirement
//my api model
class ApiModel
{
public string Content { get; set; }
}
// api call
public static async Task ApiCall()
{
var client = new RestClient("https://google.com/");
var request = new RestRequest("api/get_something", Method.Get);
var response = await client.GetAsync(request);
// i want to return like this
var customRes = new ApiModel();
customRes.Content = response.Content;
return customRes;
}
Solution 1:[1]
you have to deserialize response
public static async Task<ActionResult<ApiModel>> ApiCall()
{
.... your code
var response = await client.GetAsync(request);
if (response.IsSuccessStatusCode)
{
var json = response.Content;
var result = JsonConvert.DeserializeObject<ApiModel>(json);
return Ok(result)
//or you have to post API model, I can only guess
return Ok( new ApiModel { Content= ... I dont know what});
}
return BadRequest();
}
Solution 2:[2]
public static async Task<ApiModel> ApiCall(){
var client = new RestClient("https://google.com/");
var request = new RestRequest("api/get_something", Method.Get);
var result = client.Execute<ApiModel>(request).Data;
return result ;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
