ASP.NET MVC 5 error when consuming api with HttpClient

0

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.

    
asked by vcasas 04.05.2018 в 16:56
source

1 answer

0

This mistake I had recently, (more, I'm still solving some of the logic for this problem).

What I could find out is that when using the client, this is not released for the next request that is wanted to be made. Supposedly, using the static is part of the solution. Why do you use it in the action that generates the view?

Look at this link where it tells you a lot about HttpClient link

I hope I have guided you a little and hope someone has a better answer!

    
answered by 16.07.2018 в 15:20