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


C# Http.HttpResponseMessage类代码示例

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


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

示例1: 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

示例2: ExecuteActionFilterAsync

        public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            if (actionContext.Request.Headers.Contains("X-AccessToken"))
            {
                var tokenvalue = actionContext.Request.Headers.GetValues("X-AccessToken").FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"]))
                {
                    return continuation();
                }
            }
            else if (actionContext.Request.RequestUri.ParseQueryString() != null)
            {
                var queryValues = actionContext.Request.RequestUri.ParseQueryString();
                var tokenvalue = queryValues["token"];
                if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"]))
                {
                    return continuation();
                }
            }

            return Task.Factory.StartNew(() =>
            {
                var retur = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("This resource cannot be used without the correct access token")
                };

                return retur;
            });

        }
开发者ID:unipluss,项目名称:UniAlltid.Language,代码行数:31,代码来源:TokenAccessFilter.cs

示例3: Get

        /// <summary>
        /// Get the resource description of the api for swagger documentation
        /// </summary>
        /// <remarks>It is very convenient to have this information available for generating clients. This is the entry point for the swagger UI
        /// </remarks>
        /// <returns>JSON document representing structure of API</returns>
        public HttpResponseMessage Get()
        {
            var docProvider = (XmlCommentDocumentationProvider)GlobalConfiguration.Configuration.Services.GetDocumentationProvider();

            ResourceListing r = SwaggerGen.CreateResourceListing(ControllerContext);
            List<string> uniqueControllers = new List<string>();

            foreach (var api in GlobalConfiguration.Configuration.Services.GetApiExplorer().ApiDescriptions)
            {
                string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
                if (uniqueControllers.Contains(controllerName) ||
                      controllerName.ToUpper().Equals(SwaggerGen.SWAGGER.ToUpper())) continue;

                uniqueControllers.Add(controllerName);

                ResourceApi rApi = SwaggerGen.CreateResourceApi(api);
                r.apis.Add(rApi);
            }

            HttpResponseMessage resp = new HttpResponseMessage();

            resp.Content = new ObjectContent<ResourceListing>(r, ControllerContext.Configuration.Formatters.JsonFormatter);            
            
            return resp;
        }
开发者ID:CWISoftware,项目名称:Swagger.Net,代码行数:31,代码来源:SwaggerController.cs

示例4: CanEnrich

        public bool CanEnrich(HttpResponseMessage response) {

            var content = response.Content as ObjectContent;

            return content != null
                && (content.ObjectType == typeof(MediaModel));
        }
开发者ID:mahf,项目名称:ASPNETWebAPISamples,代码行数:7,代码来源:MediaResponseEnricher.cs

示例5: AddAndDeleteGridWidgetFromFileSystemVerifyPageToolbox

        public void AddAndDeleteGridWidgetFromFileSystemVerifyPageToolbox()
        {
            RuntimeSettingsModificator.ExecuteWithClientTimeout(800000, () =>  BAT.Macros().NavigateTo().CustomPage("~/sitefinity/pages", false));
            RuntimeSettingsModificator.ExecuteWithClientTimeout(800000, () => BAT.Macros().User().EnsureAdminLoggedIn());
            BAT.Wrappers().Backend().Pages().PagesWrapper().OpenPageZoneEditor(PageName);
            BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().SwitchEditorLayoutMode(EditorLayoutMode.Layout);
            BATFrontend.Wrappers().Backend().Widgets().GridWidgets().ClickBootstrapGridWidgetButton();
            BATFrontend.Wrappers().Backend().Pages().PageZoneEditorWrapper().DragAndDropLayoutWidgetToPlaceholder(LayoutCaption);
            BAT.Wrappers().Backend().Pages().PageLayoutEditorWrapper().VerifyLayoutWidgetPageEditor(LayoutCaption, GridCount1);
            BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().PublishPage();

            BAT.Macros().NavigateTo().CustomPage("~/" + PageName.ToLower(), false);
            BATFrontend.Wrappers().Frontend().Widgets().GridWidgets().VerifyNewGridWidgetOnTheFrontend(this.layouts);

            BAT.Arrange(this.TestName).ExecuteArrangement("DeleteGridWidgetFromFileSystem");

            BAT.Macros().NavigateTo().Pages();
            BAT.Wrappers().Backend().Pages().PagesWrapper().OpenPageZoneEditor(PageName);
            BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().SwitchEditorLayoutMode(EditorLayoutMode.Layout);
            BATFrontend.Wrappers().Backend().Widgets().GridWidgets().ClickBootstrapGridWidgetButton();
            Assert.IsFalse(
                BATFrontend.Wrappers().Backend().Pages().PageZoneEditorWrapper().IsLayoutWidgetPresentInToolbox(LayoutCaption),
                "Layout widget is found in the toolbox");

            BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().PublishPage();
            BAT.Macros().NavigateTo().CustomPage("~/" + PageName.ToLower(), false);

            // Asserts that the page is not throwing an error 500 on the frontend
            HttpResponseMessage response = new HttpResponseMessage();
            Assert.AreEqual(200, (int)response.StatusCode);
        }
开发者ID:sbschase,项目名称:feather,代码行数:31,代码来源:AutoGenerateGridWidgetToToolboxForPage.cs

示例6: ExecuteAsync

		public Task<HttpResponseMessage> ExecuteAsync( CancellationToken cancellationToken ) {
			//Request.GetOwinContext().Authentication.Challenge( LoginProvider );

			HttpResponseMessage response = new HttpResponseMessage( HttpStatusCode.Unauthorized );
			response.RequestMessage = Request;
			return Task.FromResult( response );
		}
开发者ID:jeelliott,项目名称:RestaurantReviews,代码行数:7,代码来源:ChallengeResult.cs

示例7: ThrowIfError

        public static void ThrowIfError(HttpResponseMessage response, dynamic json)
        {
            if (json == null) return;

            if (!JsonHelpers.ContainsProperty(json, Constants.ErrorProperty)) return;

            var error = json[Constants.ErrorProperty];
            if (string.IsNullOrWhiteSpace(error)) return;

            CexApiException exception;

            if (error == Constants.NonceMustBeIncremented)
            {
                exception = new CexNonceException(response, Constants.NonceMustBeIncremented);
            }
            else if (error == Constants.PermissionDenied)
            {
                exception = new CexPermissionDeniedException(response, Constants.PermissionDenied);
            }
            else if (error == Constants.InvalidApiKey)
            {
                exception = new CexInvalidApiKeyException(response, Constants.InvalidApiKey);
            }
            else
            {
                exception = new CexApiException(response, error);
            }

            throw exception;
        }
开发者ID:jordansjones,项目名称:Cex.io-Api-Client,代码行数:30,代码来源:ExceptionOracle.cs

示例8: CreateSuccessTokenResponseMessage

 public static HttpResponseMessage CreateSuccessTokenResponseMessage()
 {
     HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
     HttpContent content = new StringContent("{\"token_type\":\"Bearer\",\"expires_in\":\"3599\",\"scope\":\"some-scope1 some-scope2\",\"access_token\":\"some-access-token\",\"refresh_token\":\"OAAsomethingencryptedQwgAA\",\"id_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJlODU0YTRhNy02Y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RjZWUGlGemN4LVFkODBlaElFZEZ1cyIsInRpZCI6IjZjM2Q1MWRkLWYwZTUtNDk1OS1iNGVhLWE4MGM0ZTM2ZmU1ZSJ9\"}");
     responseMessage.Content = content;
     return responseMessage;
 }
开发者ID:AzureAD,项目名称:microsoft-authentication-library-for-dotnet,代码行数:7,代码来源:MockHelpers.cs

示例9: HandleResponseAsync

        public override Task<HttpResponseMessage> HandleResponseAsync(string linkRelation, HttpResponseMessage responseMessage)
        {
            _action(linkRelation, responseMessage);

            return base.HandleResponseAsync(linkRelation, responseMessage);
            
        }
开发者ID:hapikit,项目名称:hapikit.net,代码行数:7,代码来源:InlineResponseHandler.cs

示例10: RetryAfter_RetryHeader_100

 public void RetryAfter_RetryHeader_100()
 {
     var headers = new HttpResponseMessage().Headers;
     headers.Add("Retry-After", "100");
     var response = new FitbitResponse<string>((HttpStatusCode)429, headers, null);
     Assert.AreEqual(100, response.RetryAfter());
 }
开发者ID:lobrien,项目名称:Fitbit.NET,代码行数:7,代码来源:FitbitResponseTests.cs

示例11: WebApiResponseMessage

        public WebApiResponseMessage(HttpResponseMessage response) : base(response.Content)
        {
            this.response = response;

            this.response.Headers.ToList()
                .ForEach(h => this.messageHeaders.Add(h.Key, h.Value.ToArray()));
        }
开发者ID:RyanLiu99,项目名称:Thinktecture.IdentityModel,代码行数:7,代码来源:WebApiResponseMessage.cs

示例12: Execute

 private HttpResponseMessage Execute()
 {
     HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
     response.RequestMessage = request;
     response.ReasonPhrase = errorMessage;
     return response;
 }
开发者ID:vinhxuando,项目名称:TicketBooking,代码行数:7,代码来源:AuthenticationFailureResult.cs

示例13: ExecuteExceptionFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws

        public void ExecuteExceptionFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws()
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage();
            HttpResponseMessage response = new HttpResponseMessage();
            Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true };
            InvalidOperationException exception = new InvalidOperationException("test");
            mockAttr.Setup(a => a.OnException(It.IsAny<HttpActionExecutedContext>())).Throws(exception);
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" },
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = "OnException" }
            };

            // Act
            Exception thrown =
                Assert.Throws<InvalidOperationException>(
                    () => ((IExceptionFilter) tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None));

            // Assert
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:30,代码来源:ExceptionFilterAttributeTracerTest.cs

示例14: ExecuteExceptionFilterAsync_Traces

        public void ExecuteExceptionFilterAsync_Traces()
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage();
            HttpResponseMessage response = new HttpResponseMessage();
            Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true };
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
            TestTraceWriter traceWriter = new TestTraceWriter();
            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter);
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" },
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End,  Operation = "OnException" },
            };

            // Act
            Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);
            task.Wait();

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:25,代码来源:ExceptionFilterAttributeTracerTest.cs

示例15: PostTest

        public void PostTest()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            var result = _contactController.Post(contact);

            Assert.AreEqual(response.StatusCode, result.StatusCode);
        }
开发者ID:zannik,项目名称:APIRestTest,代码行数:7,代码来源:UnitTest1.cs


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