2016-08-01 48 views
0

我正在使用Web API 2并在ASP.Net 4中开发。这是我试图学习webapi的示例代码。有两条路线。第一条路线是给定商店的服务资源。第二条路线是商店资源路线。为什么Web API没有找到我的资源?

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapRoute(
     name: "Services", 
     url: "store/{id}/services", 
     defaults: new { controller = "Services" } 
    ); 

    routes.MapRoute(
     name: "Store", 
     url: "store/{id}", 
     defaults: new { controller = "Store", id = UrlParameter.Optional} 
    ); 
} 

第二条路线“商店”完美地工作。第一条路线是详细介绍商店中可用的所有服务。当我尝试

/API /存储/ 1 /服务

我得到404错误。有人能指点我做错了什么吗?

这里是控制器

namespace APITestter1.Controllers 
{ 
    public class ServicesController : ApiController 
    { 
     public string Get(int id, string prop = "xxx") 
     { 
      return "Hello services World!" + id + " added attribute " + prop; 
     } 

     public string Post(int id, string prop = "xxx") 
     { 
      return "Hello Post World!" + id + " added attribute " + prop; 
     } 

    } 
} 

回答

1

我不明白为什么前缀加“api”和“道具”?

我更新代码:

public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      name: "Services", 
      url: "api/store/{id}/services/{prop}", 
      defaults: new { controller = "Services", action = "store", prop = UrlParameter.Optional } 
     ); 

     routes.MapRoute(
      name: "Store", 
      url: "store/{id}", 
      defaults: new { controller = "Store", id = UrlParameter.Optional} 
     ); 
    } 


namespace APITestter1.Controllers 
{ 
    public class ServicesController : ApiController 
    { 
     [HttpGet, ActionName="store"] 
     public string Get(int id, string prop = "xxx") 
     { 
      return "Hello services World!" + id + " added attribute " + prop; 
     } 

     [HttpPost, ActionName="store"] 
     public string Post(int id, string prop = "xxx") 
     { 
      return "Hello Post World!" + id + " added attribute " + prop; 
     } 

    } 
} 
1

你在错误的文件映射您的Web API的路线。如果你正在做网页API,然后寻找WebApiConfig.cs文件,并在那里映射你的网页API路线。

您也在尝试浏览到/api/store/1/services,但在您的示例中,您将路线映射为store/{id}/services。请注意,您的路线模板中没有api

以下Web API的配置应该符合你正在尝试做

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     // Attribute routing. 
     config.MapHttpAttributeRoutes(); 

     // Convention-based routing. 
     config.Routes.MapHttpRoute(
      name: "ServicesApi", 
      routeTemplate: "api/store/{id}/services", 
      defaults: new { controller = "Services" } 
     ); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    } 
} 

你也说你的第二条路线“商店”的作品完美,但没有表现出你使用什么URL。假设它是/api/store/1那么它将工作,因为它映射到使用api/{controller}/{id}DefaultApi路由模板。

相关问题