1

我的路线:

            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: null,
                constraints: new { id = @"^\d+$" }
            );

            routes.MapHttpRoute(
                name: "ApiControllerActionRoute",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

我的方法:

// GET api/Set/All
        [ActionName("All")]
        public IEnumerable<Set> GetSets()
        {
            var sets = _repository.GetAllSets();
            return sets;
        }

        // GET api/Set/TopLevelSets
        [ActionName("TopLevelSets")]
        public IEnumerable<Set> GetTopLevelSets()
        {
            var sets = _repository.GetTopLevelSets();
            return sets.ToList();
        }

        // GET api/Set/Breadcrumbs/1
        [ActionName("Breadcrumbs")]
        public IEnumerable<Set> GetBreadCrumbs(int id)
        {
            var sets = _repository.GetBreadcrumbs(id);
            return sets.ToList();
        }

        // GET api/Set/5
        public Set GetSet(int id)
        {
            Set set = _repository.GetSet(id);
            if (set == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return set;
        }

        // PUT api/Set/5
        public HttpResponseMessage PutSet(Set set)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            _repository.UpdateSet(set);

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // POST api/Set
        public HttpResponseMessage PostSet(Set set)
        {
            if (ModelState.IsValid)
            {
                _repository.AddSet(set);
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, set);
                return response;
            }
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }

        // DELETE api/Set/5
        public HttpResponseMessage DeleteSet(int id)
        {         
            _repository.DeleteSet(id);
            return Request.CreateResponse(HttpStatusCode.OK, id);
        }

此时我正在尝试使用 localhost/api/set/1 - getSet 方法。一切似乎都与路线一致,但由于某种原因它不起作用。我错过了什么?

4

2 回答 2

2

您的默认路由未设置默认操作,因此当您使用“获取”操作时,路由引擎无法决定您是否需要 GetTopLevelSets 或 GetSet。添加默认值将解决此问题:

 routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { action = "GetSet" },
                constraints: new { id = @"^\d+$" }
            );

将它默认为您GetSet的控制器中的操作,使用:api/set (controller)/1 (id)路由。

于 2013-03-04T04:45:43.790 回答
1

您是否缺少查询的 api 部分?本地主机/ api /set/1

于 2013-03-04T03:39:12.543 回答