Exemplo n.º 1
0
        public IEnumerable <UriResolutionResult> Get()
        {
            string               routeTemplate = "movies/{genre}/{title}/{id}";
            IHttpRoute           route         = new HttpRoute(routeTemplate);
            IHttpRouteConstraint contraint     = new HttpMethodConstraint(HttpMethod.Post);

            route.Constraints.Add("httpMethod", contraint);

            string             requestUri = "http://www.artech.com/api/movies/romance/titanic/001";
            HttpRequestMessage request1   = new HttpRequestMessage(HttpMethod.Get, requestUri);
            HttpRequestMessage request2   = new HttpRequestMessage(HttpMethod.Post, requestUri);

            string root1 = "/";
            string root2 = "/api/";

            IHttpRouteData routeData1 = route.GetRouteData(root1, request1);
            IHttpRouteData routeData2 = route.GetRouteData(root1, request2);
            IHttpRouteData routeData3 = route.GetRouteData(root2, request1);
            IHttpRouteData routeData4 = route.GetRouteData(root2, request2);

            yield return(new UriResolutionResult(root1, "GET", routeData1 != null));

            yield return(new UriResolutionResult(root1, "POST", routeData2 != null));

            yield return(new UriResolutionResult(root2, "GET", routeData3 != null));

            yield return(new UriResolutionResult(root2, "POST", routeData4 != null));
        }
Exemplo n.º 2
0
        // GET: GetRouteData解决针对入栈请求的校验
        public IEnumerable <UrlResolutionResult> Get()
        {
            string     routeTemplate = "movies/{genre}/{title}/{id}";
            IHttpRoute route         = new HttpRoute(routeTemplate);
            var        constraint    = new HttpMethodConstraint(HttpMethod.Post);

            route.Constraints.Add("HttpMethod", constraint);

            string requestUri = "http://www.artech.com/api/movies/romance/titanic/001";
            //创建被检验的请求,具有相同的请求地址
            //采用Http方法不相同
            var request1 = new HttpRequestMessage(HttpMethod.Get, requestUri);
            var request2 = new HttpRequestMessage(HttpMethod.Post, requestUri);

            //不同虚拟根路径对HttpRoute的影响
            string root1 = "/";     //不可达
            string root2 = "/api/"; //可达

            IHttpRouteData routeData1 = route.GetRouteData(root1, request1);
            IHttpRouteData routeData2 = route.GetRouteData(root1, request1);
            IHttpRouteData routeData3 = route.GetRouteData(root2, request2);
            IHttpRouteData routeData4 = route.GetRouteData(root2, request2);


            yield return(new UrlResolutionResult(root1, "Get", routeData1 != null));

            yield return(new UrlResolutionResult(root1, "Post", routeData2 != null));

            yield return(new UrlResolutionResult(root2, "Get", routeData3 != null));

            yield return(new UrlResolutionResult(root2, "Post", routeData4 != null));
        }
Exemplo n.º 3
0
        //public async Task<IHttpActionResult> DeleteLink([FromODataUri] int key, string navigationProperty)
        //{
        //    Product product = await db.Products.FindAsync(key);
        //    if (product == null)
        //    {
        //        return NotFound();
        //    }

        //    switch (navigationProperty)
        //    {
        //        case "Supplier":
        //            product.Supplier = null;
        //            await db.SaveChangesAsync();
        //            return StatusCode(HttpStatusCode.NoContent);

        //        default:
        //            return NotFound();

        //    }
        //}

        // Helper method to extract the key from an OData link URI.
        private TKey GetKeyFromLinkUri <TKey>(Uri link)
        {
            TKey key = default(TKey);

            // Get the route that was used for this request.
            IHttpRoute route = Request.GetRouteData().Route;

            // Create an equivalent self-hosted route.
            IHttpRoute newRoute = new HttpRoute(route.RouteTemplate,
                                                new HttpRouteValueDictionary(route.Defaults),
                                                new HttpRouteValueDictionary(route.Constraints),
                                                new HttpRouteValueDictionary(route.DataTokens), route.Handler);

            // Create a fake GET request for the link URI.
            var tmpRequest = new HttpRequestMessage(HttpMethod.Get, link);

            // Send this request through the routing process.
            var routeData = newRoute.GetRouteData(
                Request.GetConfiguration().VirtualPathRoot, tmpRequest);

            // If the GET request matches the route, use the path segments to find the key.
            if (routeData != null)
            {
                ODataPath path    = tmpRequest.GetODataPath();
                var       segment = path.Segments.OfType <KeyValuePathSegment>().FirstOrDefault();
                if (segment != null)
                {
                    // Convert the segment into the key type.
                    key = (TKey)ODataUriUtils.ConvertFromUriLiteral(
                        segment.Value, ODataVersion.V3);
                }
            }
            return(key);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Helper method to get the odata path for an arbitrary odata uri.
        /// </summary>
        /// <param name="request">The request instance in current context</param>
        /// <param name="uri">OData uri</param>
        /// <returns>The parsed odata path</returns>
        public static ODataPath CreateODataPath(this HttpRequestMessage request, Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            var newRequest = new HttpRequestMessage(HttpMethod.Get, uri);
            var route      = request.GetRouteData().Route;

            var newRoute = new HttpRoute(
                route.RouteTemplate,
                new HttpRouteValueDictionary(route.Defaults),
                new HttpRouteValueDictionary(route.Constraints),
                new HttpRouteValueDictionary(route.DataTokens),
                route.Handler);
            var routeData = newRoute.GetRouteData(request.GetConfiguration().VirtualPathRoot, newRequest);

            if (routeData == null)
            {
                throw new InvalidOperationException("The link is not a valid odata link.");
            }

            return(newRequest.GetODataPath());
        }
Exemplo n.º 5
0
        // DFTODO - this cannot be the final solution - way to much overhead
        public static T GetKeyFromLinkUri <T>(this ODataController controller, Uri link)
        {
            Contract.Requires(null != link);

            T key = default(T);

            IHttpRoute route    = controller.Request.GetRouteData().Route;
            IHttpRoute newRoute = new HttpRoute(
                route.RouteTemplate
                ,
                new HttpRouteValueDictionary(route.Defaults)
                ,
                new HttpRouteValueDictionary(route.Constraints)
                ,
                new HttpRouteValueDictionary(route.DataTokens), route.Handler
                );

            var newRequest = new HttpRequestMessage(HttpMethod.Get, link);
            var routeData  = newRoute.GetRouteData(controller.Request.GetConfiguration().VirtualPathRoot, newRequest);

            if (null != routeData)
            {
                ODataPath path = newRequest.ODataProperties().Path;
                System.Diagnostics.Trace.Assert(null != path);
                var segment = path.Segments.OfType <KeyValuePathSegment>().FirstOrDefault();
                if (null != segment)
                {
                    key = (T)ODataUriUtils.ConvertFromUriLiteral(segment.Value, ODataVersion.V3);
                }
            }
            return(key);
        }
Exemplo n.º 6
0
        public void Invoke_CreatesUri_ThatGeneratesCorrectlyDecodedStrings(string decodedId)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers/" + decodedId);
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);
            var route   = new HttpRoute("api/customers/{id}");

            adapter.Invoke(new OwinContext(environment)).Wait();
            IHttpRouteData routeData = route.GetRouteData("/vroot", handler.Request);

            Assert.NotNull(routeData);
            Assert.Equal(decodedId, routeData.Values["id"]);
        }
Exemplo n.º 7
0
        public void GetRouteDataDoesNotMatch(string uriTemplate, string virtualPathRoot, string requestUri)
        {
            HttpRoute route = new HttpRoute(uriTemplate);

            route.Defaults.Add("controller", "Customer");
            route.Defaults.Add("id", "999");
            HttpRequestMessage request = new HttpRequestMessage();

            request.RequestUri = new Uri(requestUri);

            IHttpRouteData data = route.GetRouteData(virtualPathRoot, request);

            // Assert
            Assert.Null(data);
        }
Exemplo n.º 8
0
        public void GetRouteDataShouldMatch(string uriTemplate, string virtualPathRoot, string requestUri)
        {
            HttpRoute route = new HttpRoute(uriTemplate);

            route.Defaults.Add("controller", "Customer");
            route.Defaults.Add("id", "999");
            HttpRequestMessage request = new HttpRequestMessage();

            request.RequestUri = new Uri(requestUri);
            IHttpRouteData data = route.GetRouteData(virtualPathRoot, request);

            // Assert
            Assert.NotNull(data);
            IDictionary <string, object> expectedResult = new Dictionary <string, object>();

            expectedResult["controller"] = "Customer";
            expectedResult["id"]         = "999";
            Assert.Equal(expectedResult, data.Values, new DictionaryEqualityComparer());
        }
Exemplo n.º 9
0
        public static bool ParseSingleEntityLink(this ODataController oDataController, Uri link, out IEdmEntitySet entitySet, out object key)
        {
            Contract.Requires <ArgumentNullException>(oDataController != null);
            Contract.Requires <ArgumentNullException>(link != null);
            HttpRequestMessage request = oDataController.Request;

            // Get the route that was used for this request.
            IHttpRoute route = request.GetRouteData().Route;

            // Create an equivalent self-hosted route.
            IHttpRoute newRoute = new HttpRoute(route.RouteTemplate,
                                                new HttpRouteValueDictionary(route.Defaults),
                                                new HttpRouteValueDictionary(route.Constraints),
                                                new HttpRouteValueDictionary(route.DataTokens), route.Handler);

            // Create a fake GET request for the link URI.
            var tmpRequest = new HttpRequestMessage(HttpMethod.Get, link);

            // Send this request through the routing process.
            var routeData = newRoute.GetRouteData(request.GetRequestContext().VirtualPathRoot, tmpRequest);

            // If the GET request matches the route, use the path segments to find the key.
            if (routeData != null)
            {
                ODataPath path = tmpRequest.ODataProperties().Path;
                if (path.PathTemplate == "~/entityset/key")
                {
                    entitySet = path.EntitySet;
                    var keySegment = path.Segments.OfType <KeyValuePathSegment>().FirstOrDefault();
                    if (keySegment != null)
                    {
                        // Convert the segment into the key type.
                        key = ODataUriUtils.ConvertFromUriLiteral(keySegment.Value, ODataVersion.V3, request.ODataProperties().Model, entitySet.GetSingleKeyType());
                        return(true);
                    }
                }
            }

            entitySet = null;
            key       = null;
            return(false);
        }
Exemplo n.º 10
0
        protected HttpResponseMessage Get(string uri)
        {
            if (Handler == null)
            {
                throw new InvalidOperationException("Handler must be set by fixture subclass");
            }

            var request = new HttpRequestMessage(HttpMethod.Get, uri);

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = Configuration;

            var route     = new HttpRoute(_routeTemplate);
            var routeData = route.GetRouteData("/", request) ?? new HttpRouteData(route);

            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;

            return(new HttpMessageInvoker(Handler)
                   .SendAsync(request, new CancellationToken(false))
                   .Result);
        }
        internal static string GetSwagger()
        {
            SetupRoutesFor(typeof(TRex.Test.DummyApi.WebApiApplication).Assembly);

            var request = new HttpRequestMessage(HttpMethod.Get, "http://tempuri.org/swagger/docs/v1");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

            var route = new HttpRoute("swagger/docs/{apiVersion}");

            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route.GetRouteData("/", request);

            var messageInvoker = new HttpMessageInvoker(GetDefaultHandler());

            var result = messageInvoker.SendAsync(request, new CancellationToken(false)).Result;

            var responseContent = result.Content.ReadAsStringAsync().Result;

            return(responseContent);
        }
Exemplo n.º 12
0
        //
        public Dictionary <string, IDictionary <string, object> > CheckRouteData()
        {
            var result = new Dictionary <string, IDictionary <string, object> >();
            HttpRouteValueDictionary defaults = new HttpRouteValueDictionary();

            defaults.Add("controller", "Demo");
            defaults.Add("action", "Get");
            defaults.Add("val", 0);
            HttpRouteValueDictionary constraints = new HttpRouteValueDictionary();

            constraints.Add("val", new DoubleRouteConstraint());

            HttpRoute route             = new HttpRoute("cutomer/{controller}/{action}/{val}", defaults, constraints);
            var       customerRouteData = route.GetRouteData(RequestContext.VirtualPathRoot, Request);

            Request.GetRouteData();
            result.Add("CustomerApi", customerRouteData == null ? null : customerRouteData.Values);
            var defaultRouteData = RequestContext.RouteData.Route.GetRouteData(RequestContext.VirtualPathRoot, Request);

            result.Add("DefaultApi", defaultRouteData == null ? null : defaultRouteData.Values);
            return(result);
        }