Joh*_*ohn 3 asp.net-mvc-4 asp.net-web-api asp.net-web-api-routing
我一直在尝试使用MVC WebAPI,非常酷的东西.但我正在努力解决路线问题.
作为一个例子,我有一个webAPI项目结构,如下所示:
项目:
目前我在WebApiConfig.cs中定义了一个API路由
config.Routes.MapHttpRoute(
name: "CustomerApi",
routeTemplate: "api/customer/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
Run Code Online (Sandbox Code Playgroud)
当我只有客户相关的控制器时,这工作正常.所以我可以打电话:
但是现在我已经添加了与配置相关的产品相关控制器(当然)以获得我必须调用Uri的产品:
相反,我想:
对于产品类别,我想要类似于:
我认为我必须做的就是添加更多路线,但是我无法找到如何将各种控制器与我希望的路线联系起来?
如果我确实添加了另一条路线,我最终会将两条不同的uri路由到我建立的每个控制器.
如何实现我想要的逻辑分区?
使用Web Api 2,您可以顺利地为您的操作定义特定路由.例如 :
public class CustomerController : ApiController
{
[Route("api/customer")]
public IEnumerable<Customer> GetCustomers()
{
// ..
}
[Route("api/customer/{customerID}")]
public Customer GetCustomer(int customerID)
{
// ..
}
[Route("api/customer/CustomerAddresses/{customerID}")]
public Address GetCustomerAddresses(int customerID)
{
// ...
}
}
public class ProductController : ApiController
{
[Route("api/product")]
public IEnumerable<Product> GetProducts()
{
// ..
}
[Route("api/product/{prodID}")]
public Product GetProduct(int prodID)
{
// ..
}
[Route("api/product/categories/{catID}")]
public Category GetCategory(int catID)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1562 次 |
| 最近记录: |