Pia*_*swi 5 asp.net url asp.net-web-api
我正在创建我的第一个ASP.NET Web API.我试图遵循标准的REST URL.我的API会返回搜索结果记录.我的网址应该是 -
../api/categories/{categoryId}/subcategories/{subCategoryId}/records?SearchCriteria
我打算使用oData进行搜索和IIS上的基本/摘要式身份验证.我的问题在于嵌套资源.在我返回搜索结果之前,我需要检查用户是否可以访问此类别和子类别.现在我开始创建我的Visual Studio 2012 - MVC4/Web API项目.在App_Start文件夹中,我认为有两个文件是URL和资源相关的顺序.
1.RouteConfig.cs
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
2.WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
使用此模型,如果我的URL是../api/records?SearchCriteria,它可以正常工作,但它不是我上面提到的URL设计.我知道我必须做更多的阅读,但到目前为止还没有找到正确的文章.需要您的建议如何实现我的URL以及这两个文件需要进行哪些更改.或者,我在这里缺少一些其他配置吗?提前致谢.
小智 2
假设你有一个名为categories的控制器,你的WebApiConfig.cs可能有一个像这样的路由来匹配你想要的url(我个人会保留/records部分):
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{categoryId}/subcategories/{subCategoryId}",
defaults: new { controller = "categories", categoryId = somedefaultcategory,
subCategoryId = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
方法可能如下所示:
// 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))
{
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您只想返回类别而不返回子类别怎么办?在第一个更通用的路线之后,您需要一条额外的路线:
config.Routes.MapHttpRoute(
name: "Categories",
routeTemplate: "api/{controller}/{categoryId}",
defaults: new { controller = "categories", categoryId = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
有两种方法,例如:
// search a single category
public IQueryable<SearchRecord> Get(int categoryId, string SearchCriteria = "")
{
}
// search all categories
public IQueryable<SearchRecord> Get(string SearchCriteria = "")
{
}
Run Code Online (Sandbox Code Playgroud)