public static async Task <JsonResult> getShakespeareTranslated(string content) { var client = new RestClient("https://api.funtranslations.com/translate/shakespeare.json"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.RequestFormat = DataFormat.Json; request.AddParameter("text", content); var cancellationTokenSource = new CancellationTokenSource(); IRestResponse response = await client.ExecuteAsync(request, cancellationTokenSource.Token); if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests) { return(new JsonResult(ErrorMessage.tooManyRequest) { StatusCode = StatusCodes.Status429TooManyRequests }); } if (response.ErrorException != null) { string message = ErrorMessage.unExpectedShakespeareError; var shakespeareException = new ApplicationException(message, response.ErrorException); throw shakespeareException; } ShakespeareResponse shakespeareResponse = JsonConvert.DeserializeObject <ShakespeareResponse>(response.Content); return(new JsonResult(shakespeareResponse.Contents.Translated) { StatusCode = StatusCodes.Status200OK // Status code here }); }
public async Task <string> Transform(string description) { try { var request = new ShakespeareRequest() { Text = description }; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(request)); ByteArrayContent byteContent = new ByteArrayContent(buffer); HttpResponseMessage result = await _client.PostAsync(_configuration.EndpointBaseUrl, byteContent); if (result.StatusCode != HttpStatusCode.OK) { throw new PokemonHttpException(result.ReasonPhrase, result.StatusCode); } byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); string strResult = await result.Content.ReadAsStringAsync(); ShakespeareResponse decodedResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <ShakespeareResponse>(strResult); return(decodedResponse.contents.translated); } catch (WebException exc) { throw new PokemonHttpException(exc.Message, HttpStatusCode.RequestTimeout); } catch (TaskCanceledException) { throw new PokemonHttpException("Shakespeare endpoint not available.", HttpStatusCode.RequestTimeout); } catch (Exception exc) { if (exc.Message.Contains("404 (Not Found)")) { throw new PokemonHttpException(exc.Message, System.Net.HttpStatusCode.NotFound); } if (exc.HResult == -2147467259) { throw new PokemonHttpException(exc.Message, HttpStatusCode.RequestTimeout); } throw new PokemonHttpException(exc.Message, System.Net.HttpStatusCode.InternalServerError); } }