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


C# Http.HttpRequestMessage类代码示例

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


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

示例1: ChangeUserProfile

        public static async Task<bool> ChangeUserProfile(String name, String url, String description, String location,
            UserAccountEntity userAccountEntity)
        {
            if (userAccountEntity.GetAccessToken().Equals("refresh"))
            {
                await Auth.RefreshAccessToken(userAccountEntity);
            }
            var param = new Dictionary<String, String>();
            if (!string.IsNullOrEmpty(name)) param.Add("name", name);
            if (!string.IsNullOrEmpty(url)) param.Add("url", url);
            if (!string.IsNullOrEmpty(location)) param.Add("location", location);
            if (!string.IsNullOrEmpty(description)) param.Add("description", description);

            var theAuthClient = new HttpClient();
            HttpContent header = new FormUrlEncodedContent(param);
            var request = new HttpRequestMessage(HttpMethod.Post, EndPoints.ACCOUNT_UPDATE) {Content = header};
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
            try
            {
                HttpResponseMessage response = await theAuthClient.SendAsync(request);
                return response.IsSuccessStatusCode;
            }
            catch (Exception)
            {
                return false;
            }
        }
开发者ID:happy-ryo,项目名称:CrouMetro,代码行数:27,代码来源:UserManager.cs

示例2: SendAsync

    protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {

      if (HttpContext.Current.User.Identity.IsAuthenticated) {
        return await base.SendAsync(request, cancellationToken);
      }
      if (!CanHandleAuthentication(request)) {
        return await base.SendAsync(request, cancellationToken);
      }
      bool isAuthenticated;
      try {
        isAuthenticated = Authenticate(request);
      }
      catch (Exception) {
        return CreateUnauthorizedResponse();
      }
      if (isAuthenticated) {
        var response = await base.SendAsync(request, cancellationToken);

        // add token cookie value
        IEnumerable<CookieHeaderValue> ccoll = new CookieHeaderValue[] { new CookieHeaderValue(_TokenName, _Token) };
        response.Headers.AddCookies(ccoll);
        
        return response.StatusCode == HttpStatusCode.Unauthorized ? CreateUnauthorizedResponse() : response;
      }
      return CreateUnauthorizedResponse();
    }
开发者ID:pillesoft,项目名称:JolTudomE,代码行数:26,代码来源:LoginMessageHandler.cs

示例3: AppendAuthenticationHeader_ExpiredAccountSession

        public async Task AppendAuthenticationHeader_ExpiredAccountSession()
        {
            var cachedAccountSession = new AccountSession
            {
                AccessToken = "token",
            };

            this.authenticationProvider.CurrentAccountSession = cachedAccountSession;

            using (var httpRequestMessage = new HttpRequestMessage())
            {
                try
                {
                    await this.authenticationProvider.AppendAuthHeaderAsync(httpRequestMessage);
                }
                catch (OneDriveException oneDriveException)
                {
                    Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), oneDriveException.Error.Code, "Unexpected error code.");
                    Assert.AreEqual(
                        "Failed to retrieve a valid authentication token for the user.",
                        oneDriveException.Error.Message,
                        "Unexpected error message.");

                    throw;
                }
            }
        }
开发者ID:Galiafalt,项目名称:onedrive-sdk-csharp,代码行数:27,代码来源:AuthenticationProviderTests.cs

示例4: Translate

        public string Translate(string text, string from, string to)
        {
            using (var client = new HttpClient())
            {
                var url = string.Format(
                        _translatorApiUrlFormat,
                        HttpUtility.UrlEncode(text),
                        HttpUtility.UrlEncode(from),
                        HttpUtility.UrlEncode(to));

                using (var message = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", GetAccessToken());

                    using (var result = client.SendAsync(message).Result)
                    {
                        if (!result.IsSuccessStatusCode)
                        {
                            throw new TrosiTranslationException(result.Content.ReadAsStringAsync().Result);
                        }

                        using (var responseStream = result.Content.ReadAsStreamAsync().Result)
                        {
                            var serializer = new DataContractSerializer(typeof(string));

                            return serializer.ReadObject(responseStream) as string;
                        }
                    }
                }
            }
        }
开发者ID:rhysgodfrey,项目名称:Trosi,代码行数:31,代码来源:Translator.cs

示例5: SendAsync

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url = new Java.Net.URL(java_uri);

            var body = default(RequestBody);
            if (request.Content != null) {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                body = RequestBody.Create(MediaType.Parse(request.Content.Headers.ContentType.MediaType), bytes);
            }

            var builder = new Request.Builder()
                .Method(request.Method.Method.ToUpperInvariant(), body)
                .Url(url);

            var keyValuePairs = request.Headers
                .Union(request.Content != null ?
                    (IEnumerable<KeyValuePair<string, IEnumerable<string>>>)request.Content.Headers :
                    Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>());

            foreach (var kvp in keyValuePairs) builder.AddHeader(kvp.Key, String.Join(",", kvp.Value));

            cancellationToken.ThrowIfCancellationRequested();

            var rq = builder.Build();
            var call = client.NewCall(rq);
            cancellationToken.Register(() => call.Cancel());

            var resp = default(Response);
            try {
                resp = await call.EnqueueAsync().ConfigureAwait(false);
            } catch (IOException ex) {
                if (ex.Message.ToLowerInvariant().Contains("canceled")) {
                    throw new OperationCanceledException();
                }

                throw;
            }

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());
            if (respBody != null) {
                var content = new ProgressStreamContent(respBody.ByteStream(), cancellationToken);
                content.Progress = getAndRemoveCallbackFromRegister(request);
                ret.Content = content;
            } else {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            var respHeaders = resp.Headers();
            foreach (var k in respHeaders.Names()) {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return ret;
        }
开发者ID:rickykaare,项目名称:ModernHttpClient,代码行数:60,代码来源:OkHttpNetworkHandler.cs

示例6: AttriubteRouting_SelectsExpectedControllerAndAction

        [InlineData("GET", "http://localhost/Customers(12)/NS.SpecialCustomer/NS.GetSalary()", "GetSalaryFromSpecialCustomer_12")] // call function on derived entity type
        public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri,
            string expectedResult)
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            var controllers = new[] { typeof(CustomersController), typeof(MetadataAndServiceController), typeof(OrdersController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));

            HttpConfiguration config = new HttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Replace(typeof(IAssembliesResolver), resolver);

            config.MapODataServiceRoute("odata", "", model.Model);

            HttpServer server = new HttpServer(config);
            config.EnsureInitialized();

            HttpClient client = new HttpClient(server);
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            if (!response.IsSuccessStatusCode)
            {
                Assert.False(true, await response.Content.ReadAsStringAsync());
            }
            var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>();
            Assert.Equal(expectedResult, result.Value);
        }
开发者ID:richarddwelsh,项目名称:aspnetwebstack,代码行数:33,代码来源:AttributeRoutingTest.cs

示例7: MessageHandler

        private bool MessageHandler(HttpRequestMessage request, HttpResponseMessage response)
        {
            if (request.RequestUri.OriginalString.Contains("status"))
            {
                try
                {
                    int code =
                        Convert.ToInt32(
                            request.RequestUri.OriginalString.Substring(request.RequestUri.OriginalString.Length - 3, 3));
                    HttpStatusCode status = (HttpStatusCode)code;
                    throw new HttpStatusException(status);
                }
                catch (HttpStatusException)
                {
                    throw;
                }
                catch (Exception)
                {

                    throw new HttpStatusException(HttpStatusCode.BadRequest);
                }
            }
            else
                response.Content = new StringContent(string.Format(Html, DateTime.Now.ToString("s"), request.RequestUri.OriginalString), Encoding.UTF8, "text/html");
            return true;
        }
开发者ID:rherlt,项目名称:SimpleUniversalWebserver,代码行数:26,代码来源:MainPage.xaml.cs

示例8: Put

        public HttpResponseMessage Put(HttpRequestMessage request, int betId, int userId, [FromBody]BetUser betUser)
        {
            if (!ModelState.IsValid)
            {
                return request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (betId != betUser.BetId || userId != betUser.UserId)
            {
                return request.CreateResponse(HttpStatusCode.BadRequest);
            }

            try
            {
                this.dataService.UpdateBetUser(betUser);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (this.dataService.GetBetUser(betId, userId) == null)
                {
                    return request.CreateResponse(HttpStatusCode.NotFound);
                }
                else
                {
                    throw;
                }
            }

            //seriallize the object
            return request.CreateResponse<BetUser>(HttpStatusCode.OK, betUser);
        }
开发者ID:SeanNguyen,项目名称:SimpleBetAspNet4,代码行数:30,代码来源:BetUserController.cs

示例9: GetSuggestion

        public HttpResponseMessageWrapper<Suggestion> GetSuggestion(HttpRequestMessage req, Guid id)
        {
            Operation operation = null;
            HttpStatusCode code = AuthenticateUser(req);
            if (code != HttpStatusCode.OK)
            {   // user not authenticated
                return ReturnResult<Suggestion>(req, operation, code);
            }

            try
            {
                Suggestion suggestion = this.SuggestionsStorageContext.Suggestions.Single<Suggestion>(s => s.ID == id);
                if (!ValidateEntityOwnership(suggestion.EntityID, suggestion.EntityType))
                {   // entity associated with suggestions does not belong to the authenticated user, return 403 Forbidden
                    TraceLog.TraceError("Associated entity does not belong to current user)");
                    return ReturnResult<Suggestion>(req, operation, HttpStatusCode.Forbidden);
                }
                var response = ReturnResult<Suggestion>(req, operation, suggestion, HttpStatusCode.OK);
                response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true };
                return response;
            }
            catch (Exception ex)
            {   // suggestion not found - return 404 Not Found
                TraceLog.TraceException("Resource not found", ex);
                return ReturnResult<Suggestion>(req, operation, HttpStatusCode.NotFound);
            }
        }
开发者ID:ogazitt,项目名称:product,代码行数:27,代码来源:SuggestionResource.cs

示例10: SendRequestAsync_ReturnsSingleErrorResponse

        public void SendRequestAsync_ReturnsSingleErrorResponse()
        {
            HttpRequestMessage[] requests = new HttpRequestMessage[]
                {
                    new HttpRequestMessage(HttpMethod.Get, "http://example.com"),
                    new HttpRequestMessage(HttpMethod.Post, "http://example.com"),
                    new HttpRequestMessage(HttpMethod.Put, "http://example.com")
                };
            ChangeSetRequestItem requestItem = new ChangeSetRequestItem(requests);

            Mock<HttpMessageInvoker> invoker = new Mock<HttpMessageInvoker>(new HttpServer());
            invoker.Setup(i => i.SendAsync(It.IsAny<HttpRequestMessage>(), CancellationToken.None))
                .Returns<HttpRequestMessage, CancellationToken>((req, c) =>
                {
                    if (req.Method == HttpMethod.Post)
                    {
                        return Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest));
                    }
                    return Task.FromResult(new HttpResponseMessage());
                });

            var response = requestItem.SendRequestAsync(invoker.Object, CancellationToken.None).Result;

            var changesetResponse = Assert.IsType<ChangeSetResponseItem>(response);
            Assert.Equal(1, changesetResponse.Responses.Count());
            Assert.Equal(HttpStatusCode.BadRequest, changesetResponse.Responses.First().StatusCode);
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:27,代码来源:ChangeSetRequestItemTest.cs

示例11: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
            string identifier = GetUserIdentifier(request);
            if (String.IsNullOrEmpty(identifier))
                return CreateResponse(request, HttpStatusCode.Forbidden, "Could not identify client.");

            string cacheKey = GetCacheKey(identifier);
            long requestCount = 0;
            using (IRedisClient client = _clientsManager.GetClient()) {
                requestCount = client.IncrementValueBy(cacheKey, 1);
                if (requestCount == 1)
                    client.ExpireEntryIn(cacheKey, _period);
            }

            Task<HttpResponseMessage> response = null;
            long maxRequests = _maxRequestsForUserIdentifier(identifier);
            if (requestCount > maxRequests)
                response = CreateResponse(request, HttpStatusCode.Conflict, _message);
            else
                response = base.SendAsync(request, cancellationToken);

            return response.ContinueWith(task => {
                long remaining = maxRequests - requestCount;
                if (remaining < 0)
                    remaining = 0;

                HttpResponseMessage httpResponse = task.Result;
                httpResponse.Headers.Add("RateLimit-Limit", maxRequests.ToString());
                httpResponse.Headers.Add("RateLimit-Remaining", remaining.ToString());

                return httpResponse;
            });
        }
开发者ID:priestd09,项目名称:Exceptionless,代码行数:32,代码来源:ThrottlingHandler.cs

示例12: ByPostShouldReturnCorrectResponse

        public void ByPostShouldReturnCorrectResponse()
        {
            var controller = typeof(CategoriesController);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
            );

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var httpServer = new HttpServer(config);
            var httpInvoker = new HttpMessageInvoker(httpServer);

            using (httpInvoker)
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://test.com/api/categories/1"),
                    Method = HttpMethod.Get
                };

                var result = httpInvoker.SendAsync(request, CancellationToken.None).Result;

                Assert.IsNotNull(result);
            }
        }
开发者ID:Team-Hypnos,项目名称:Gallery,代码行数:30,代码来源:CategoriesIntegrationTests.cs

示例13: Parameter_Constructor

        public void Parameter_Constructor()
        {
            HttpRequestMessage[] requests = new HttpRequestMessage[0];
            ChangeSetRequestItem requestItem = new ChangeSetRequestItem(requests);

            Assert.Same(requests, requestItem.Requests);
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:7,代码来源:ChangeSetRequestItemTest.cs

示例14: NoRequestContentType_Throws_IfMultipleActionsWithConstraints

        public async Task NoRequestContentType_Throws_IfMultipleActionsWithConstraints()
        {
            // Arrange
            var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client = server.CreateClient();
            var request = new HttpRequestMessage(
                HttpMethod.Post,
                "http://localhost/ConsumesAttribute_AmbiguousActions/CreateProduct");

            // Act
            var response = await client.SendAsync(request);
            var exception = response.GetServerException();

            // Assert
            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
            Assert.Equal(typeof(AmbiguousActionException).FullName, exception.ExceptionType);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                "Multiple actions matched. The following actions matched route data and had all constraints " +
                "satisfied:" + PlatformNormalizer.GetNewLinesAsUnderscores(2) + "ActionConstraintsWebSite." +
                    "ConsumesAttribute_NoFallBackActionController." +
                "CreateProduct" + PlatformNormalizer.GetNewLinesAsUnderscores(1) + "ActionConstraintsWebSite." +
                    "ConsumesAttribute_NoFallBackActionController.CreateProduct",
                exception.ExceptionMessage);
        }
开发者ID:notami18,项目名称:Mvc,代码行数:25,代码来源:ConsumesAttributeTests.cs

示例15: TestRoute

        public void TestRoute(string url, string verb, Type type, string actionName)
        {
            //Arrange
            url = url.Replace("{apiVersionNumber}", this.ApiVersionNumber);
            url = Host + url;

            //Act
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(verb), url);

            IHttpControllerSelector controller = this.GetControllerSelector();
            IHttpActionSelector action = this.GetActionSelector();

            IHttpRouteData route = this.Config.Routes.GetRouteData(request);
            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;
            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = this.Config;

            HttpControllerDescriptor controllerDescriptor = controller.SelectController(request);

            HttpControllerContext context = new HttpControllerContext(this.Config, route, request)
            {
                ControllerDescriptor = controllerDescriptor
            };

            var actionDescriptor = action.SelectAction(context);

            //Assert
            Assert.NotNull(controllerDescriptor);
            Assert.NotNull(actionDescriptor);
            Assert.Equal(type, controllerDescriptor.ControllerType);
            Assert.Equal(actionName, actionDescriptor.ActionName);
        }
开发者ID:abinabrahamanchery,项目名称:mixerp,代码行数:31,代码来源:GetPartyTypeIdByPartyCodeRouteTests.cs


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