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


C# HttpRequestMessage.GetCorsRequestContext方法代码示例

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


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

示例1: GetCorsRequestContext_CachesTheContext

        public void GetCorsRequestContext_CachesTheContext()
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, "http://example.com/test");
            request.Headers.Add("Origin", "foo");
            request.Headers.Add("Host", "example.com");
            request.Headers.Add("Access-Control-Request-Method", "bar");

            CorsRequestContext result = request.GetCorsRequestContext();
            CorsRequestContext result2 = request.GetCorsRequestContext();

            Assert.Same(result, result2);
        }
开发者ID:balajivasudevan,项目名称:aspnetwebstack,代码行数:12,代码来源:CorsHttpRequestMessageExtensionsTest.cs

示例2: SendAsync

        /// <summary>
        /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation.
        /// </summary>
        /// <param name="request">The HTTP request message to send to the server.</param>
        /// <param name="cancellationToken">A cancellation token to cancel operation.</param>
        /// <returns>
        /// Returns <see cref="T:System.Threading.Tasks.Task`1" />. The task object representing the asynchronous operation.
        /// </returns>
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            CorsRequestContext corsRequestContext = request.GetCorsRequestContext();
            if (corsRequestContext != null)
            {
                try
                {
                    if (corsRequestContext.IsPreflight)
                    {
                        return await HandleCorsPreflightRequestAsync(request, corsRequestContext, cancellationToken);
                    }
                    else
                    {
                        return await HandleCorsRequestAsync(request, corsRequestContext, cancellationToken);
                    }
                }
                catch (Exception exception)
                {
                    return HandleException(request, exception);
                }
            }
            else
            {
                return await base.SendAsync(request, cancellationToken);
            }
        }
开发者ID:balajivasudevan,项目名称:aspnetwebstack,代码行数:36,代码来源:CorsMessageHandler.cs

示例3: GetCorsPolicyAsync

 public async Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     var corsRequestContext = request.GetCorsRequestContext();
     var originRequested = corsRequestContext.Origin;
     if (await IsOriginApproved(originRequested))
     {
         // Grant CORS request
         var policy = new CorsPolicy();
         policy.Origins.Add(originRequested);
         policy.Methods.Add("GET");
         policy.Methods.Add("POST");
         policy.Methods.Add("PUT");
         policy.Methods.Add("DELETE");
         policy.Methods.Add("PATCH");
         policy.Methods.Add("OPTIONS");
         policy.Headers.Add("accept");
         policy.Headers.Add("content-type");
         policy.Headers.Add("X-Auth-Token");
         policy.Headers.Add("Origin");
         policy.ExposedHeaders.Add("DataServiceVersion");
         policy.ExposedHeaders.Add("MaxDataServiceVersion");
         policy.ExposedHeaders.Add("X-Auth-Token");
         policy.SupportsCredentials = true;
         return policy;
     }
     // Reject CORS request
     return null;
 }
开发者ID:johnbrunnings,项目名称:Neat,代码行数:28,代码来源:CustomCORSPolicyAttribute.cs

示例4: EvaluatePolicy_Trace_ContainsHttpRequest

        public void EvaluatePolicy_Trace_ContainsHttpRequest()
        {
            // Arrange
            HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Options, "http://example.com/test");
            httpRequest.Headers.Add("Origin", "foo");
            CorsRequestContext corsRequestContext = httpRequest.GetCorsRequestContext();

            Mock<ITraceWriter> traceWriterMock = new Mock<ITraceWriter>();
            traceWriterMock
                .Setup(t => t.Trace(httpRequest, It.IsAny<string>(), It.IsAny<TraceLevel>(), It.IsAny<Action<TraceRecord>>()))
                .Verifiable();

            Mock<ICorsEngine> corsEngineMock = new Mock<ICorsEngine>();
            corsEngineMock
                .Setup(engine => engine.EvaluatePolicy(corsRequestContext, It.IsAny<CorsPolicy>()))
                .Returns(new CorsResult());

            CorsEngineTracer tracer = new CorsEngineTracer(corsEngineMock.Object, traceWriterMock.Object);

            // Act
            tracer.EvaluatePolicy(corsRequestContext, new CorsPolicy());

            // Assert 
            traceWriterMock.Verify();
        }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:25,代码来源:CorsEngineTracerTest.cs

示例5: GetCorsPolicyAsync

 public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request)
 {
     return _traceWriter.TraceBeginEndAsync<CorsPolicy>(
         request,
         TraceCategories.CorsCategory,
         TraceLevel.Info,
         _innerPolicyProvider.GetType().Name,
         MethodName,
         beginTrace: (tr) =>
         {
             tr.Message = String.Format(CultureInfo.CurrentCulture, SRResources.TraceCorsRequestContext, request.GetCorsRequestContext());
         },
         execute: () => _innerPolicyProvider.GetCorsPolicyAsync(request),
         endTrace: (tr, policy) =>
         {
             if (policy != null)
             {
                 tr.Message = String.Format(CultureInfo.CurrentCulture, SRResources.TraceEndPolicyReturned, policy);
             }
             else
             {
                 tr.Message = SRResources.TraceEndNoPolicyReturned;
             }
         },
         errorTrace: null);
 }
开发者ID:brianly,项目名称:aspnetwebstack,代码行数:26,代码来源:CorsPolicyProviderTracer.cs

示例6: GetCorsPolicyProvider

        public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
        {
            ICorsPolicyProvider policyProvider = null;

            _traceWriter.TraceBeginEnd(
                request,
                TraceCategories.CorsCategory,
                TraceLevel.Info,
                _innerPolicyProviderFactory.GetType().Name,
                MethodName,
                beginTrace: (tr) =>
                {
                    tr.Message = String.Format(CultureInfo.CurrentCulture, SRResources.TraceCorsRequestContext, request.GetCorsRequestContext());
                },
                execute: () => { policyProvider = _innerPolicyProviderFactory.GetCorsPolicyProvider(request); },
                endTrace: (tr) =>
                {
                    if (policyProvider != null)
                    {
                        tr.Message = String.Format(CultureInfo.CurrentCulture, SRResources.TraceEndPolicyProviderReturned, policyProvider);
                    }
                    else
                    {
                        tr.Message = SRResources.TraceEndNoPolicyProviderReturned;
                    }
                },
                errorTrace: null);

            if (policyProvider != null)
            {
                return new CorsPolicyProviderTracer(policyProvider, _traceWriter);
            }

            return null;
        }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:35,代码来源:CorsPolicyProviderFactoryTracer.cs

示例7: GetCorsPolicyProvider

        public virtual ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            CorsRequestContext corsRequestContext = request.GetCorsRequestContext();
            HttpActionDescriptor actionDescriptor = null;
            if (corsRequestContext.IsPreflight)
            {
                HttpRequestMessage targetRequest = new HttpRequestMessage(new HttpMethod(corsRequestContext.AccessControlRequestMethod), request.RequestUri);

                request.RegisterForDispose(targetRequest);

                try
                {
                    foreach (var property in request.Properties)
                    {
                        // The RouteData and HttpContext from the preflight request properties contain information
                        // relevant to the preflight request and not the actual request, therefore we need to exclude them.
                        if (property.Key != HttpPropertyKeys.HttpRouteDataKey &&
                            property.Key != HttpContextBaseKey)
                        {
                            targetRequest.Properties.Add(property.Key, property.Value);
                        }
                    }

                    HttpConfiguration config = request.GetConfiguration();
                    if (config == null)
                    {
                        throw new InvalidOperationException(SRResources.NoConfiguration);
                    }

                    IHttpRouteData routeData = config.Routes.GetRouteData(request);
                    if (routeData == null)
                    {
                        // No route data found for selecting action with EnableCorsAttribute, thus no ICorsPolicyProvider is returned
                        // and let the CorsMessageHandler flow the request to the normal Web API pipeline.
                        return null;
                    }

                    actionDescriptor = SelectAction(targetRequest, routeData, config);
                }
                catch
                {
                    if (DefaultPolicyProvider != null)
                    {
                        return DefaultPolicyProvider;
                    }
                    throw;
                }
            }
            else
            {
                actionDescriptor = request.GetActionDescriptor();
            }

            return GetCorsPolicyProvider(actionDescriptor);
        }
开发者ID:ahmetgoktas,项目名称:aspnetwebstack,代码行数:60,代码来源:AttributeBasedPolicyProviderFactory.cs

示例8: GetCorsRequestContext_ReturnsOrigin

        public void GetCorsRequestContext_ReturnsOrigin()
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, "http://example.com/test");
            request.Headers.Add("Origin", "foo");

            CorsRequestContext result = request.GetCorsRequestContext();

            Assert.Equal("foo", result.Origin);
        }
开发者ID:balajivasudevan,项目名称:aspnetwebstack,代码行数:9,代码来源:CorsHttpRequestMessageExtensionsTest.cs

示例9: GetCorsRequestContext_ReturnsRequestMethod

        public void GetCorsRequestContext_ReturnsRequestMethod()
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, "http://example.com/test");
            request.Headers.Add("Origin", "foo");
            request.Headers.Add("Access-Control-Request-Method", "bar");

            CorsRequestContext result = request.GetCorsRequestContext();

            Assert.Equal("bar", result.AccessControlRequestMethod);
        }
开发者ID:balajivasudevan,项目名称:aspnetwebstack,代码行数:10,代码来源:CorsHttpRequestMessageExtensionsTest.cs

示例10: GetCorsPolicyProvider

        public ICorsPolicyProvider GetCorsPolicyProvider(
          HttpRequestMessage request)
        {
            var route = request.GetRouteData();
            var controller = (string)route.Values["controller"];
            var corsRequestContext = request.GetCorsRequestContext();
            var originRequested = corsRequestContext.Origin;
            var policy = GetPolicyForControllerAndOrigin(
              controller, originRequested);

            return new CustomPolicyProvider(policy);
        }
开发者ID:robyvandamme,项目名称:angular.net,代码行数:12,代码来源:DynamicPolicyProviderFactory.cs

示例11: GetCorsPolicyProvider

        public virtual ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            CorsRequestContext corsRequestContext = request.GetCorsRequestContext();
            HttpActionDescriptor actionDescriptor = null;
            if (corsRequestContext.IsPreflight)
            {
                HttpRequestMessage targetRequest = new HttpRequestMessage(new HttpMethod(corsRequestContext.AccessControlRequestMethod), request.RequestUri);
                try
                {
                    foreach (var property in request.Properties)
                    {
                        // The RouteData and HttpContext from the preflight request properties contain information
                        // relevant to the preflight request and not the actual request, therefore we need to exclude them.
                        if (property.Key != HttpPropertyKeys.HttpRouteDataKey &&
                            property.Key != HttpContextBaseKey)
                        {
                            targetRequest.Properties.Add(property.Key, property.Value);
                        }
                    }
                    actionDescriptor = SelectAction(targetRequest);
                }
                catch
                {
                    if (DefaultPolicyProvider != null)
                    {
                        return DefaultPolicyProvider;
                    }
                    throw;
                }
                finally
                {
                    if (targetRequest != null)
                    {
                        request.RegisterForDispose(targetRequest);
                    }
                }
            }
            else
            {
                actionDescriptor = request.GetActionDescriptor();
            }

            return GetCorsPolicyProvider(actionDescriptor);
        }
开发者ID:samgithub-duplicate,项目名称:aspnetwebstack,代码行数:49,代码来源:AttributeBasedPolicyProviderFactory.cs

示例12: GetCorsPolicyProvider_Preflight_ReturnsExpectedPolicyProvider

        public void GetCorsPolicyProvider_Preflight_ReturnsExpectedPolicyProvider(string httpMethod, string path, Type expectedProviderType)
        {
            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/sample" + path);
            request.Headers.Add("Origin", "http://localhost");
            request.Headers.Add(CorsConstants.AccessControlRequestMethod, httpMethod);
            HttpConfiguration config = new HttpConfiguration();
            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            IHttpRoute route = config.Routes.MapHttpRoute("default", "{controller}/{id}", new { id = RouteParameter.Optional });
            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route.GetRouteData("/", request);

            ICorsPolicyProvider provider = providerFactory.GetCorsPolicyProvider(request);

            Assert.True(request.GetCorsRequestContext().IsPreflight);
            Assert.IsType(expectedProviderType, provider);
        }
开发者ID:brianly,项目名称:aspnetwebstack,代码行数:16,代码来源:AttributeBasedPolicyProviderFactoryTest.cs

示例13: GetCorsPolicyAsync

        public async Task<CorsPolicy> GetCorsPolicyAsync( HttpRequestMessage request, CancellationToken cancellationToken )
        {
            var requestInfo = request.GetCorsRequestContext();
            var origin = requestInfo.Origin;

            // Check if request is from an authorized origin
            if ( await IsOriginValid(origin))
            {
                // Valid request
                var policy = new CorsPolicy { AllowAnyHeader = true, AllowAnyMethod = true };
                policy.Origins.Add( origin );
                return policy;
            }

            // Invalid Request
            return null;
        }
开发者ID:NewSpring,项目名称:Rock,代码行数:17,代码来源:EnableCorsFromOriginAttribute.cs

示例14: GetCorsPolicyProvider

        public virtual ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            CorsRequestContext corsRequestContext = request.GetCorsRequestContext();
            HttpActionDescriptor actionDescriptor = null;
            if (corsRequestContext.IsPreflight)
            {
                HttpRequestMessage targetRequest = new HttpRequestMessage(new HttpMethod(corsRequestContext.AccessControlRequestMethod), request.RequestUri);
                try
                {
                    foreach (var property in request.Properties)
                    {
                        targetRequest.Properties.Add(property.Key, property.Value);
                    }
                    actionDescriptor = SelectAction(targetRequest);
                }
                catch
                {
                    if (DefaultPolicyProvider != null)
                    {
                        return DefaultPolicyProvider;
                    }
                    throw;
                }
                finally
                {
                    if (targetRequest != null)
                    {
                        request.RegisterForDispose(targetRequest);
                    }
                }
            }
            else
            {
                actionDescriptor = request.GetActionDescriptor();
            }

            return GetCorsPolicyProvider(actionDescriptor);
        }
开发者ID:brianly,项目名称:aspnetwebstack,代码行数:43,代码来源:AttributeBasedPolicyProviderFactory.cs

示例15: GetCorsPolicyProvider_Preflight_ReturnsDefaultPolicyProvider_WhenActionSelectionFails

        public void GetCorsPolicyProvider_Preflight_ReturnsDefaultPolicyProvider_WhenActionSelectionFails()
        {
            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();
            ICorsPolicyProvider mockProvider = new Mock<ICorsPolicyProvider>().Object;
            providerFactory.DefaultPolicyProvider = mockProvider;
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/sample");
            request.Headers.Add("Origin", "http://localhost");
            request.Headers.Add(CorsConstants.AccessControlRequestMethod, "RandomMethod");
            HttpConfiguration config = new HttpConfiguration();
            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            IHttpRoute route = config.Routes.MapHttpRoute("default", "{controller}/{id}", new { id = RouteParameter.Optional });
            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route.GetRouteData("/", request);

            ICorsPolicyProvider provider = providerFactory.GetCorsPolicyProvider(request);

            Assert.True(request.GetCorsRequestContext().IsPreflight);
            Assert.Same(mockProvider, provider);
        }
开发者ID:brianly,项目名称:aspnetwebstack,代码行数:18,代码来源:AttributeBasedPolicyProviderFactoryTest.cs


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