private void TryBuildRequestBody(AsyncCallback requestSuccessCallback, Action requestTimeoutCallback, TimedRequest request, MusicClientCommand apiMethod) { var requestBody = apiMethod.BuildRequestBody(); request.WebRequest.Method = apiMethod.HttpMethod.ToString().ToUpperInvariant(); if (requestBody != null) { var requestState = new RequestState(request, requestBody, requestSuccessCallback, requestTimeoutCallback); request.WebRequest.ContentType = apiMethod.ContentType; request.WebRequest.BeginGetRequestStream(this.RequestStreamCallback, requestState); } else { // No request body, just make the request immediately request.BeginGetResponse(requestSuccessCallback, requestTimeoutCallback, request); } }
/// <summary> /// Writes request data to the request stream /// </summary> /// <param name="ar">The async response</param> private void RequestStreamCallback(IAsyncResult ar) { var requestState = (RequestState)ar.AsyncState; try { Stream streamResponse = requestState.TimedRequest.WebRequest.EndGetRequestStream(ar); byte[] byteArray = Encoding.UTF8.GetBytes(requestState.RequestBody); streamResponse.Write(byteArray, 0, byteArray.Length); streamResponse.Dispose(); TimedRequest request = requestState.TimedRequest; request.BeginGetResponse(requestState.SuccessCallback, requestState.TimeoutCallback, request); } catch (WebException ex) { DebugLogger.Instance.WriteLog("WebException in RequestStreamCallback: {0}", ex); requestState.TimeoutCallback(); } }