I've been learning C# over the past month and started to learn about HTTP requests using the HttpClient
class. Right now I have a basic controller in my MVC project
private readonly HttpClient _client = new HttpClient();
private HttpResponseMessage response = new HttpResponseMessage();
public IActionResult Index() {
return View();
}
[HttpGet("/data")]
async public Task < string > Data(int ? postId) {
if (postId != null) {
response = await _client.GetAsync("https://jsonplaceholder.typicode.com/comments?postId=" + postId);
} else {
response = await _client.GetAsync("https://jsonplaceholder.typicode.com/comments");
}
if (response.IsSuccessStatusCode) {
return response.Content.ReadAsStringAsync().Result;
}
return "There was an error!";
}
This works perfectly fine, except I wanted to know if it's the 'right' way of doing things. I initiated the HttpClient and HttpResponseMessage when the controller class in initialized when the web app starts up, but should I do this inside the GET route? I read somewhere on Microsoft's website it's good to initialize only once per application.