D-W
D-W

Reputation: 5341

WebApi - PostAsync

Im having trouble with this, I dont why, it must be something im doing wrong. I've had to rewrite to get it working but it smells all wrong, however it works.

So this is what I tried first and it does not work, as the statuscode of 500 was returned, but this is because it was not waiting for a response, I need it to wait

[HttpPost]
public async Task<JsonResult> Booking(string model)
{
    //do some bits.
    var a = new JavaScriptSerializer().Serialize(e);
    var booking = new HttpClient();
    HttpContent content = new StringContent(a,Encoding.UTF8);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    HttpResponseMessage response = await booking.PostAsync("https://webapi.domain.com/Booking/Post", content);
    var aa = response.StatusCode //500 Internal Error
}

So I rewrote

[HttpPost]
public async Task<JsonResult> Booking(string model)
{
    //do some bits.
    var a = new JavaScriptSerializer().Serialize(e);
    var booking = new HttpClient();
    HttpContent content = new StringContent(a,Encoding.UTF8);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    HttpResponseMessage response = await booking.PostAsync("https://webapi.domain.com/Booking/Post", content);
    var t = new Stopwatch();

    while (response.StatusCode ==HttpStatusCode.InternalServerError)
    {
        t.Start();
        var zzzz = response.ReasonPhrase;
        if (t.ElapsedMilliseconds >10000)
        {
            response.StatusCode = HttpStatusCode.RequestTimeout;
            t.Stop();
        }
    }
    var aa = response.StatusCode //201 Created
}

And this works and returns me my 201, ugly, but can anyone tell me and show me what i'm doing wrong?

Upvotes: 1

Views: 840

Answers (1)

usr
usr

Reputation: 171178

The server has a timing dependent bug. It goes away when you use the debugger to give it enough time to avoid the crash.

An asynchronous module or handler completed while an asynchronous operation was still pending

Looks like something with async.

The client is not at fault and the while (response.StatusCode ==HttpStatusCode.InternalServerError) loop does nothing. It does not even change the timing at the server. Your usage of the debugger probably did that and the two effect were confounded in your interpretation.

Fix the server, now that you know where to look.

Upvotes: 1

Related Questions