当前位置: 首页>>代码示例>>C#>>正文


C# HttpCompletionOption类代码示例

本文整理汇总了C#中HttpCompletionOption的典型用法代码示例。如果您正苦于以下问题:C# HttpCompletionOption类的具体用法?C# HttpCompletionOption怎么用?C# HttpCompletionOption使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpCompletionOption类属于命名空间,在下文中一共展示了HttpCompletionOption类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SendAsync

        /// <summary>
        /// Send request async.
        /// </summary>
        /// <param name="requestMessage">
        /// The request message.
        /// </param>
        /// <param name="completionOption">
        /// The completion option.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        protected async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage requestMessage,
            HttpCompletionOption completionOption = HttpCompletionOption.ResponseHeadersRead)
        {
            Debug.Assert(this.Logger != null, "this.Logger != null");
            Debug.Assert(this.HttpClient != null, "this.Logger != null");

            try
            {
                if (this.Logger.IsDebugEnabled)
                {
                    this.Logger.Debug("Send request ({0}): {1}.", requestMessage.Method, requestMessage.RequestUri);
                }

                HttpResponseMessage responseMessage = await this.HttpClient.SendAsync(requestMessage, completionOption);

                if (this.Logger.IsDebugEnabled)
                {
                    await this.Logger.LogResponseAsync(requestMessage.RequestUri.ToString(), responseMessage);
                }

                return responseMessage;
            }
            catch (Exception exception)
            {
                this.Logger.Error(exception, "Exception while sending request, Method: {0}, Uri: {1}.", requestMessage.Method, requestMessage.RequestUri);
                throw;
            }
        }
开发者ID:Narinyir,项目名称:Framework,代码行数:41,代码来源:WebServiceBase.cs

示例2: SingleClient_ManyGets_Async

 public async Task SingleClient_ManyGets_Async(int numRequests, int dop, HttpCompletionOption completionOption)
 {
     string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
     using (var client = new HttpClient())
     {
         await ForCountAsync(numRequests, dop, i => CreateServerAndGetAsync(client, completionOption, responseText));
     }
 }
开发者ID:tstringer,项目名称:corefx,代码行数:8,代码来源:HttpClientMiniStressTest.cs

示例3: sendHttpAsync

 private Task<HttpResponseMessage> sendHttpAsync(HttpClient client, HttpRequestMessage message, HttpCompletionOption completionOption, CancellationToken cancelationToken)
 {
     if (customMessageFunc == null)
     {
         customMessageFunc = buildHttpResponseMessage;
     }
     var task = Task.Run(customMessageFunc);
     return task;
 }
开发者ID:adasescu,项目名称:cf-dotnet-sdk-1,代码行数:9,代码来源:MockClient.cs

示例4: MaximumRetryAttemptedException

        /// <summary>
        /// Custom implementation of the IHttpProvider.SendAsync method to handle retry logic
        /// </summary>
        /// <param name="request">The HTTP Request Message</param>
        /// <param name="completionOption">The completion option</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The result of the asynchronous request</returns>
        /// <remarks>See here for further details: https://graph.microsoft.io/en-us/docs/overview/errors</remarks>
        Task<HttpResponseMessage> IHttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
        {
            Task<HttpResponseMessage> result = null;

            // Retry logic variables
            int retryAttempts = 0;
            int backoffInterval = this._delay;

            // Loop until we need to retry
            while (retryAttempts < this._retryCount)
            {
                try
                {
                    // Make the request
                    result = base.SendAsync(request, completionOption, cancellationToken);

                    // And return the response in case of success
                    return (result);
                }
                // Or handle any ServiceException
                catch (ServiceException ex)
                {
                    // Check if the is an InnerException
                    if (ex.InnerException != null)
                    {
                        // And if it is a WebException
                        var wex = ex.InnerException as WebException;
                        if (wex != null)
                        {
                            var response = wex.Response as HttpWebResponse;
                            // Check if request was throttled - http status code 429
                            // Check is request failed due to server unavailable - http status code 503
                            if (response != null && (response.StatusCode == (HttpStatusCode)429 || response.StatusCode == (HttpStatusCode)503))
                            {
                                Log.Warning(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_SendAsyncRetry, backoffInterval);

                                //Add delay for retry
                                Thread.Sleep(backoffInterval);

                                //Add to retry count and increase delay.
                                retryAttempts++;
                                backoffInterval = backoffInterval * 2;
                            }
                            else
                            {
                                Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_SendAsyncRetryException, wex.ToString());
                                throw;
                            }
                        }
                    }
                    throw;
                }
            }

            throw new MaximumRetryAttemptedException(string.Format("Maximum retry attempts {0}, has be attempted.", this._retryCount));
        }
开发者ID:s-KaiNet,项目名称:PnP-Sites-Core,代码行数:64,代码来源:PnPHttpProvider.cs

示例5: SendAsync

		/// <summary>
		/// Creates and asynchronously sends an HttpRequestMethod, disposing HttpClient if AutoDispose it true.
		/// Mainly used to implement higher-level extension methods (GetJsonAsync, etc).
		/// </summary>
		/// <returns>A Task whose result is the received HttpResponseMessage.</returns>
		public async Task<HttpResponseMessage> SendAsync(HttpMethod verb, HttpContent content = null, CancellationToken? cancellationToken = null, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) {
			try {
				var request = new HttpRequestMessage(verb, this.Url) { Content = content };
				request.SetFlurlSettings(this.Settings);
				return await HttpClient.SendAsync(request, completionOption, cancellationToken ?? CancellationToken.None);
			}
			finally {
				if (AutoDispose) Dispose();
			}
		}
开发者ID:damirjuretic,项目名称:Flurl,代码行数:15,代码来源:FlurlClient.cs

示例6: ManyClients_ManyGets

 public void ManyClients_ManyGets(int numRequests, int dop, HttpCompletionOption completionOption)
 {
     string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
     Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
     {
         using (var client = new HttpClient())
         {
             CreateServerAndGet(client, completionOption, responseText);
         }
     });
 }
开发者ID:tstringer,项目名称:corefx,代码行数:11,代码来源:HttpClientMiniStressTest.cs

示例7: SendAsync

		/// <summary>
		/// Creates and asynchronously sends an HttpRequestMethod, disposing HttpClient if AutoDispose it true.
		/// Mainly used to implement higher-level extension methods (GetJsonAsync, etc).
		/// </summary>
		/// <returns>A Task whose result is the received HttpResponseMessage.</returns>
		public async Task<HttpResponseMessage> SendAsync(HttpMethod verb, HttpContent content = null, CancellationToken? cancellationToken = null, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) {
			try {
				var request = new HttpRequestMessage(verb, this.Url) { Content = content };
				// mechanism for passing ad-hoc data to the MessageHandler
				request.Properties.Add("AllowedHttpStatusRanges", AllowedHttpStatusRanges);
				return await HttpClient.SendAsync(request, completionOption, cancellationToken ?? CancellationToken.None);
			}
			finally {
				if (AutoDispose) Dispose();
			}
		}
开发者ID:carolynvs,项目名称:Flurl,代码行数:16,代码来源:FlurlClient.cs

示例8: SendAsync

        public static async Task<HttpResponseMessage> SendAsync(this HttpClient httpClient, HttpRequestMessage request,
            HttpCompletionOption completionOption, CancellationToken cancellationToken,
            Uri referrer, long? fromBytes, long? toBytes)
        {
            if (null != referrer)
                request.Headers.Referer = referrer;

            if (null != fromBytes || null != toBytes)
                request.Headers["Range"] = new RangeHeaderValue(fromBytes, toBytes).ToString();

            return await SendRequestAsync(httpClient, request, completionOption, cancellationToken);
        }
开发者ID:henricj,项目名称:phonesm,代码行数:12,代码来源:WinRtHttpClientExtensions.cs

示例9: SendAsync

        public static async Task<HttpResponseMessage> SendAsync(this HttpClient httpClient, HttpRequestMessage request,
            HttpCompletionOption completionOption, CancellationToken cancellationToken,
            Uri referrer, long? fromBytes, long? toBytes)
        {
            if (null != referrer)
                request.Headers.Referrer = referrer;

            if (null != fromBytes || null != toBytes)
                request.Headers.Range = new RangeHeaderValue(fromBytes, toBytes);

            return await httpClient.SendAsync(request, completionOption, cancellationToken).ConfigureAwait(false);
        }
开发者ID:henricj,项目名称:phonesm,代码行数:12,代码来源:HttpClientExtensions.cs

示例10: SendAsync

 public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption)
 {
     //client.FollowRedirections = followRedirections;
     //try
     //{
         return client.SendAsync(request, completionOption);
     //}
     //finally
     //{
     //    client.FollowRedirections = true;
     //}
 }
开发者ID:CXuesong,项目名称:App2,代码行数:12,代码来源:PortableWebClient.cs

示例11: GetAsync

        public static async Task<HttpResponseMessage> GetAsync(this HttpClient httpClient, Uri uri,
            HttpCompletionOption completionOption, CancellationToken cancellationToken)
        {
            try
            {
                return await httpClient.GetAsync(uri, completionOption).AsTask(cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                HttpClientExceptionTranslator.ThrowBetterHttpClientException(ex, cancellationToken);

                throw;
            }
        }
开发者ID:henricj,项目名称:phonesm,代码行数:14,代码来源:WinRtHttpClientExtensions.cs

示例12: ExecuteAsync

        public static async Task<HttpResponseMessage> ExecuteAsync(this Uri uri, HttpMethod method,
            HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead, double timeout = 100.0)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(timeout);

                    return await client.SendAsync(new HttpRequestMessage(method, uri), completionOption);
                }
            }
            catch
            {
                return null;
            }
        }
开发者ID:haroldma,项目名称:Audiotica,代码行数:17,代码来源:UriExtensions.cs

示例13: SendAsync

        public Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, HttpCompletionOption option, CancellationToken token)
        {
            #if NET_3_5
            if(_connectionCount >= _connectionLimit) {
                return Task.Delay(500).ContinueWith(t => SendAsync(message, option, token)).Unwrap();
            }

            Interlocked.Increment(ref _connectionCount);
            #else
            return _sendSemaphore?.WaitAsync()?.ContinueWith(t =>
            {
            #endif
                var challengeResponseAuth = Authenticator as IChallengeResponseAuthenticator;
                if (challengeResponseAuth != null) {
                    _authHandler.Borrow(x => x.Authenticator = challengeResponseAuth);
                    challengeResponseAuth.PrepareWithRequest(message);
                }

                var httpClient = default(HttpClient);
                if(!_httpClient.AcquireTemp(out httpClient)) {
                    return null;
                }


                (Authenticator as ICustomHeadersAuthorizer)?.AuthorizeRequest(message);
                return httpClient.SendAsync(message, option, token);
            #if !NET_3_5
            })?.Unwrap()?.ContinueWith(t =>
            {
                _sendSemaphore?.Release();
                if(t.IsFaulted) {
                    var e = t.Exception;
                    if(Misc.UnwrapAggregate(e) is ObjectDisposedException) {
                        return null;
                    }

                    throw e;
                }

                return t.Result;
            });
            #endif
        }
开发者ID:jonfunkhouser,项目名称:couchbase-lite-net,代码行数:43,代码来源:CouchbaseLiteHttpClient.cs

示例14: SendAsync

        public virtual async Task<HttpResponseMessage> SendAsync(HttpRequest httpRequest, HttpCompletionOption completionOption, CancellationToken cancellationToken)
        {
            ThrowIfDisposed();

            OnBeforeSend(httpRequest);

            using (var message = CreateHttpRequestMessage(httpRequest))
            {
                var response = await HttpClient.SendAsync(message, completionOption, cancellationToken).ForAwait();

                if (ShouldFollowResponse(response))
                {
                    using (var followMessage = CreateHttpRequestMessage(httpRequest))
                    {
                        followMessage.RequestUri = response.Headers.Location;
                        return await HttpClient.SendAsync(followMessage, completionOption, cancellationToken).ForAwait();
                    }
                }

                OnAfterSend(response);

                return response;
            }
        }
开发者ID:aldass,项目名称:mycouch,代码行数:24,代码来源:Connection.cs

示例15: SendAsyncWorker

		async Task<HttpResponseMessage> SendAsyncWorker (HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
		{
			using (var lcts = CancellationTokenSource.CreateLinkedTokenSource (cts.Token, cancellationToken)) {
				lcts.CancelAfter (timeout);

				var task = base.SendAsync (request, lcts.Token);
				if (task == null)
					throw new InvalidOperationException ("Handler failed to return a value");
					
				var response = await task.ConfigureAwait (false);
				if (response == null)
					throw new InvalidOperationException ("Handler failed to return a response");

				//
				// Read the content when default HttpCompletionOption.ResponseContentRead is set
				//
				if (response.Content != null && (completionOption & HttpCompletionOption.ResponseHeadersRead) == 0) {
					await response.Content.LoadIntoBufferAsync (MaxResponseContentBufferSize).ConfigureAwait (false);
				}
					
				return response;
			}
		}
开发者ID:LevNNN,项目名称:mono,代码行数:23,代码来源:HttpClient.cs


注:本文中的HttpCompletionOption类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。