public UnexpectedResponseTypeCodeException(System.Net.HttpStatusCode expectedStatusCode, System.Net.HttpStatusCode receivedStatusCode) : base(string.Format( "Unexpected status code response recived. Expected {0:S}, received {1:S}.", expectedStatusCode.ToString(), receivedStatusCode.ToString()), null) { this.ExpectedStatusCode = expectedStatusCode; this.ReceivedStatusCode = receivedStatusCode; }
/// <summary> /// send globalStringPath='globalStringPath', /// pathItemStringPath='pathItemStringPath', localStringPath='localStringPath', /// globalStringQuery='globalStringQuery', /// pathItemStringQuery='pathItemStringQuery', /// localStringQuery='localStringQuery' /// </summary> /// <param name='localStringPath'> /// should contain value 'localStringPath' /// </param> /// <param name='pathItemStringPath'> /// A string value 'pathItemStringPath' that appears in the path /// </param> /// <param name='localStringQuery'> /// should contain value 'localStringQuery' /// </param> /// <param name='pathItemStringQuery'> /// A string value 'pathItemStringQuery' that appears as a query parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse> GetAllWithValuesWithHttpMessagesAsync(string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (localStringPath == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "localStringPath"); } if (pathItemStringPath == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "pathItemStringPath"); } if (this.Client.GlobalStringPath == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.GlobalStringPath"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>(); tracingParameters.Add("localStringPath", localStringPath); tracingParameters.Add("localStringQuery", localStringQuery); tracingParameters.Add("pathItemStringPath", pathItemStringPath); tracingParameters.Add("pathItemStringQuery", pathItemStringQuery); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetAllWithValues", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/globalStringQuery/pathItemStringQuery/localStringQuery").ToString(); _url = _url.Replace("{localStringPath}", System.Uri.EscapeDataString(localStringPath)); _url = _url.Replace("{pathItemStringPath}", System.Uri.EscapeDataString(pathItemStringPath)); _url = _url.Replace("{globalStringPath}", System.Uri.EscapeDataString(this.Client.GlobalStringPath)); System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>(); if (localStringQuery != null) { _queryParameters.Add(string.Format("localStringQuery={0}", System.Uri.EscapeDataString(localStringQuery))); } if (pathItemStringQuery != null) { _queryParameters.Add(string.Format("pathItemStringQuery={0}", System.Uri.EscapeDataString(pathItemStringQuery))); } if (this.Client.GlobalStringQuery != null) { _queryParameters.Add(string.Format("globalStringQuery={0}", System.Uri.EscapeDataString(this.Client.GlobalStringQuery))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public TaskrowWebException(System.Net.HttpStatusCode httpStatusCode, string message, System.Exception innerException) : base(message, innerException) { this.HttpStatusCode = httpStatusCode; }
public void SearchInternalServerErrorTests(ResourceId resourceId, System.Net.HttpStatusCode expectedCode) { var request = SearchRequestComposer.GetBuilderWithRestrictions(resourceId).TextFilter($"{resourceId}.P_RandomString", OperatorType.Eq, null, SearchValue); PerformFailedSearchTest(request, expectedCode); }
/// <summary>is this a success status code</summary> /// <param name="status">status code</param> /// <returns>true if status is between 200-299</returns> internal static bool SuccessStatusCode(System.Net.HttpStatusCode status) { return(200 <= (int)status && (int)status < 300); }
/// <summary> /// Constructor de la clase /// </summary> /// <param name="ResourceString">Llave del recurso a emplear</param> /// <param name="Parameters">Arreglo de parámetros de tipo string</param> public GaleException(System.Net.HttpStatusCode statusCode, string resourceString, params string[] parameters) : base() { Build(statusCode, resourceString, parameters); }
public DeclinedPayoutException(System.Net.HttpStatusCode statusCode, string responseBody, PayoutErrorResponse errorResponse) : base(BuildMessage(errorResponse), statusCode, responseBody, errorResponse?.ErrorId, errorResponse?.Errors) { this._errorResponse = errorResponse; }
/// <summary> /// Cancel booking /// </summary> /// <param name='id'> /// Booking ID /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse> DeleteBookingWithHttpMessagesAsync(System.Guid id, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>(); tracingParameters.Add("id", id); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "DeleteBooking", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/bookings/{id}").ToString(); _url = _url.Replace("{id}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(id, this.SerializationSettings).Trim('"'))); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 400 && (int)_statusCode != 404) { var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Search for accommodations /// </summary> /// <param name='searchText'> /// Search terms /// </param> /// <param name='page'> /// Page number /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <System.Collections.Generic.IList <SearchResult> > > SearchWithHttpMessagesAsync(string searchText = default(string), int?page = default(int?), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>(); tracingParameters.Add("searchText", searchText); tracingParameters.Add("page", page); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Search", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Search").ToString(); System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>(); if (searchText != null) { _queryParameters.Add(string.Format("searchText={0}", System.Uri.EscapeDataString(searchText))); } if (page != null) { _queryParameters.Add(string.Format("page={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(page, this.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 400) { var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse <System.Collections.Generic.IList <SearchResult> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <System.Collections.Generic.IList <SearchResult> >(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public static Result <T> FromHttpStatusCode <T>(System.Net.HttpStatusCode statusCode) where T : class { return(new Result <T> { Code = HttpStatusCodeToStatusCode(statusCode), }); }
public HttpRequestExceptionEx(System.Net.HttpStatusCode code, string message, Exception inner) : base(message, inner) { HttpCode = code; }
public HttpRequestExceptionEx(System.Net.HttpStatusCode code, string message) : this(code, message, null) { }
public HttpRequestExceptionEx(System.Net.HttpStatusCode code) : this(code, null, null) { }
/// <summary> /// Creates a new service exception. /// </summary> /// <param name="error">The error that triggered the exception.</param> /// <param name="innerException">The possible innerException.</param> /// <param name="responseHeaders">The HTTP response headers from the response.</param> /// <param name="statusCode">The HTTP status code from the response.</param> public ServiceException(Error error, System.Net.Http.Headers.HttpResponseHeaders responseHeaders, System.Net.HttpStatusCode statusCode, Exception innerException = null) : base(error?.ToString(), innerException) { this.Error = error; this.ResponseHeaders = responseHeaders; this.StatusCode = statusCode; }
public RequestException(System.Net.HttpStatusCode httpStatusCode, string errorContent) { this.HttpStatusCode = httpStatusCode; ErrorContent = errorContent; }
private bool CheckStatusCode(System.Net.HttpStatusCode httpStatusCode) { return(httpStatusCode == System.Net.HttpStatusCode.OK); }
internal HttpResponseException(System.Net.HttpStatusCode statusCode, string message) : base(message) { this.HttpStatusCode = statusCode; }
/// <summary> /// Book an accommodation /// </summary> /// <param name='accommodationId'> /// Accommodation ID /// </param> /// <param name='bookingData'> /// Booking details /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <BookingRepresentation> > CreateBookingWithHttpMessagesAsync(System.Guid accommodationId, BookingData bookingData = default(BookingData), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (bookingData != null) { bookingData.Validate(); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>(); tracingParameters.Add("accommodationId", accommodationId); tracingParameters.Add("bookingData", bookingData); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateBooking", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/accommodations/{accommodationId}/bookings").ToString(); _url = _url.Replace("{accommodationId}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(accommodationId, this.SerializationSettings).Trim('"'))); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (bookingData != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(bookingData, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 400 && (int)_statusCode != 404) { var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse <BookingRepresentation>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <BookingRepresentation>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// OAuth認証のアクセストークン取得。PIN入力用の後段 /// </summary> /// <remarks> /// 事前にAuthenticatePinFlowRequestを呼んで、ブラウザで認証後に表示されるPINを入力してもらい、その値とともに呼び出すこと /// </remarks> /// <param name="accessTokenUrl">アクセストークンの取得先URL</param> /// <param name="requestUri">AuthenticatePinFlowRequestで取得したリクエストトークン</param> /// <param name="pinCode">Webで認証後に表示されるPINコード</param> /// <returns>取得結果真偽値</returns> public HttpStatusCode AuthenticatePinFlow(string accessTokenUrl, string requestToken, string pinCode) { // PIN-based flow if (string.IsNullOrEmpty(requestToken)) { throw new Exception("Sequence error.(requestToken is blank)"); } // アクセストークン取得 string content = ""; NameValueCollection accessTokenData; HttpStatusCode httpCode = this.GetOAuthToken(new Uri(accessTokenUrl), pinCode, requestToken, null, ref content); if (httpCode != HttpStatusCode.OK) { return(httpCode); } accessTokenData = base.ParseQueryString(content); if (accessTokenData != null) { this.token = accessTokenData["oauth_token"]; this.tokenSecret = accessTokenData["oauth_token_secret"]; // サービスごとの独自拡張対応 if (!string.IsNullOrEmpty(this.userIdentKey)) { this.authorizedUsername = accessTokenData[this.userIdentKey]; } else { this.authorizedUsername = ""; } if (!string.IsNullOrEmpty(this.userIdIdentKey)) { try { this.authorizedUserId = Convert.ToInt64(accessTokenData[this.userIdIdentKey]); } catch (Exception) { this.authorizedUserId = 0; } } else { this.authorizedUserId = 0; } if (string.IsNullOrEmpty(token)) { throw new InvalidDataException("Token is null."); } return(HttpStatusCode.OK); } else { throw new InvalidDataException("Return value is null."); } }
public WebApiException(string requestedUrl, System.Net.HttpStatusCode statusCode, Exception innerException) : base("Error occured when calling WebApi", innerException) { RequestedUrl = requestedUrl; StatusCode = statusCode; }
/// <summary> /// OAuth認証のアクセストークン取得。xAuth方式 /// </summary> /// <param name="accessTokenUrl">アクセストークンの取得先URL</param> /// <param name="username">認証用ユーザー名</param> /// <param name="password">認証用パスワード</param> /// <returns>取得結果真偽値</returns> public HttpStatusCode AuthenticateXAuth(Uri accessTokenUrl, string username, string password, ref string content) { // ユーザー・パスワードチェック if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { throw new Exception("Sequence error.(username or password is blank)"); } // xAuthの拡張パラメータ設定 Dictionary <string, string> parameter = new Dictionary <string, string>(); parameter.Add("x_auth_mode", "client_auth"); parameter.Add("x_auth_username", username); parameter.Add("x_auth_password", password); // アクセストークン取得 HttpStatusCode httpCode = this.GetOAuthToken(accessTokenUrl, "", "", parameter, ref content); if (httpCode != HttpStatusCode.OK) { return(httpCode); } NameValueCollection accessTokenData = base.ParseQueryString(content); if (accessTokenData != null) { this.token = accessTokenData["oauth_token"]; this.tokenSecret = accessTokenData["oauth_token_secret"]; // サービスごとの独自拡張対応 if (!string.IsNullOrEmpty(this.userIdentKey)) { this.authorizedUsername = accessTokenData[this.userIdentKey]; } else { this.authorizedUsername = ""; } if (!string.IsNullOrEmpty(this.userIdIdentKey)) { try { this.authorizedUserId = Convert.ToInt64(accessTokenData[this.userIdIdentKey]); } catch (Exception) { this.authorizedUserId = 0; } } else { this.authorizedUserId = 0; } if (string.IsNullOrEmpty(token)) { throw new InvalidDataException("Token is null."); } return(HttpStatusCode.OK); } else { throw new InvalidDataException("Return value is null."); } }
public ApiException(System.Net.HttpStatusCode statusCode, string responseBody, string errorId, IList <APIError> errors) : this("the Ingenico ePayments platform returned an error response", statusCode, responseBody, errorId, errors) { }
protected IActionResult MakeResponse(System.Net.HttpStatusCode statusCode, object payload = null) { return(new Response(statusCode, payload).ToActionResult()); }
private static partial void UserProfileError( ILogger logger, System.Net.HttpStatusCode status, string headers, string body);
protected IActionResult MakeErrorResponse(System.Net.HttpStatusCode statusCode, Error error) { return(new Response(statusCode, new Error[] { error }).ToActionResult()); }
protected StatusCodeResult StatusCode(System.Net.HttpStatusCode code) => StatusCode((int)code);
public static bool IsSuccess(this System.Net.HttpStatusCode code) { return(code == System.Net.HttpStatusCode.OK || code == System.Net.HttpStatusCode.Created); }
/// <summary> /// Upload file /// </summary> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// File name to upload. Name has to be spelled exactly as written here. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <System.IO.Stream> > UploadFileWithHttpMessagesAsync(System.IO.Stream fileContent, string fileName, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (fileContent == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fileContent"); } if (fileName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fileName"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>(); tracingParameters.Add("fileContent", fileContent); tracingParameters.Add("fileName", fileName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "UploadFile", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent(); if (fileContent != null) { System.Net.Http.StreamContent _fileContent = new System.Net.Http.StreamContent(fileContent); _fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); System.IO.FileStream _fileContentAsFileStream = fileContent as System.IO.FileStream; if (_fileContentAsFileStream != null) { System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data"); _contentDispositionHeaderValue.Name = "fileContent"; _contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name; _fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue; } _multiPartContent.Add(_fileContent, "fileContent"); } if (fileName != null) { System.Net.Http.StringContent _fileName = new System.Net.Http.StringContent(fileName, System.Text.Encoding.UTF8); _multiPartContent.Add(_fileName, "fileName"); } _httpRequest.Content = _multiPartContent; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse <System.IO.Stream>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public AspNetCoreExampleException( string message, System.Net.HttpStatusCode statusCode = System.Net.HttpStatusCode.InternalServerError ) : base(message) => this.HttpStatusCode = statusCode;
/// <summary> /// Get complex types with array property which is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <ArrayWrapperInner> > GetEmptyWithHttpMessagesAsync(System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString(); System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse <ArrayWrapperInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <ArrayWrapperInner>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
private static Stream GenerateErrorResponse(string errorDetails, string errorMessage, System.Net.HttpStatusCode errorCode) { Connector.QueryResult queryResult = new Connector.QueryResult(); queryResult.Success = false; queryResult.Message = errorMessage; queryResult.AddOutputParam("code", errorCode); if (!string.IsNullOrEmpty(errorDetails)) { queryResult.AddOutputParam("details", string.Format("[message:\"{0}\"]", errorDetails)); } return(queryResult.ToStream()); }
public DropNetResult(RestSharp.RestResponse m) { StatusCode = m.StatusCode; }
public JsonStreamHttpActionResult(HttpRequestMessage request, System.Net.HttpStatusCode code, T responseData) { this.responseData = responseData; this.request = request; this.statusCode = code; }