2013-05-13 100 views
5

我正在创建我的第一个ASP.NET Web API。我正在尝试遵循标准的REST URL。我的API将返回搜索结果记录。我的URL应该是 -URL中的Web API嵌套资源

../api/categories/{categoryId}/subcategories/{subCategoryId}/records?SearchCriteria

我打算使用OData的搜索和基本/摘要式身份验证在IIS。我的问题是嵌套的资源。在我返回搜索结果之前,我需要检查用户是否有权访问此类别和子类别。 现在我创建了我的Visual Studio 2012 - MVC4/Web API项目以开始。在App_Start文件夹中,我认为有2个文件是URL和资源相关的顺序。

1.RouteConfig.cs

routes.MapRoute(
name: "Default", 
url: "{controller}/{action}/{id}", 
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
); 

2.WebApiConfig.cs

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

在这种模式下,它工作正常,如果我的网址是../api/records?SearchCriteria但不是我上面提到的URL设计。我明白我不得不做更多的阅读,但至今无法找到正确的文章。需要您提供关于如何实现我的URL以及这两个文件需要哪些更改的建议。或者,我还有其他一些配置在这里吗?提前致谢。

回答

2

假设你有一个名为类别,你WebApiConfig.cs可能有这样的路线,以符合您需要的网址(我个人离开/记录部分关闭)控制器:

config.Routes.MapHttpRoute(
    name: "DefaultApi", 
    routeTemplate: "api/{controller}/{categoryId}/subcategories/{subCategoryId}", 
    defaults: new { controller = "categories", categoryId = somedefaultcategory, 
     subCategoryId = RouteParameter.Optional } 
); 

和方法看起来是这样的:

// search a single subcategory 
public IQueryable<SearchRecord> Get(int categoryId, int subCategoryId = 0, string SearchCriteria = "") 
{   
    // test subCategoryId for non-default value to return records for a single 
    // subcategory; otherwise, return records for all subcategories 
    if (subCategoryId != default(int)) 
    { 
    } 
} 

但是,如果你想也只返回类别和子类别不是什么?你需要第一个是比较通用的后附加的路径:

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

有两个方法,如:

// search a single category 
public IQueryable<SearchRecord> Get(int categoryId, string SearchCriteria = "") 
{ 
} 
// search all categories 
public IQueryable<SearchRecord> Get(string SearchCriteria = "") 
{ 
} 
3

Asp.net的Web API 2提供属性路由开箱。您可以在单个操作方法或全局级别上定义Route

如:

[RoutePrefix("api/books")] 
public class BooksController : ApiController 
{ 
    // GET api/books 
    [Route("")] 
    public IEnumerable<Book> Get() { ... } 

    // GET api/books/5 
    [Route("{id:int}")] 
    public Book Get(int id) { ... } 
} 

您可以访问this链接的详细信息,属性中的Web路由:

[Route("customers/{customerId}/orders/{orderId}")] 
public Order GetOrderByCustomer(int customerId, int orderId) { ... } 

您也可以通过使用[RoutePrefix]属性设置一个共同的前缀为整个控制器API 2.