2013-05-13 108 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.