當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。