I am consuming an api through the HttpClient service which works fine, but at the time of making another request it throws me an uncontrolled exception. With this last I mean that when making the first request it returns the answer to me well, but when I give it f5 and make another request it launches this ...
This instance has already initiated one or more requests. You can only modify the properties before sending the first request.
Description: Unhandled exception when executing the current Web request. Check the stack trace for more information about the error and where it originated in the code.
Exception details: System.InvalidOperationException: This instance has already initiated one or more requests. You can only modify the properties before sending the first request.
Line 16: public async Task IndexAsync () Line 17: { Line 18: client.BaseAddress = new Uri (" link "); Line 19: client.DefaultRequestHeaders.Accept.Clear (); Line 20: client.DefaultRequestHeaders.Accept.Add (
How can I solve it? This is my code.
Controller:
// GET: Testing
public async Task<ActionResult> IndexAsync()
{
client.BaseAddress = new Uri("http://0.0.0.0:5000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("authorization");
var persona = await GetProductAsync("api");
return View(persona);
}
My static method of the HttpClient service
static HttpClient client = new HttpClient();
My method that gives me back the response
static async Task<object> GetProductAsync(string path)
{
object Obj = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
Obj = await response.Content.ReadAsAsync<Persona>();
}
return Obj;
}
It should be noted that all this code I have in a file named NombreController.cs would ideally be the same could guide me how to separate it to be able to reuse it in all the queries that I must do in the application. Thanks.