在ASP.NET Web API中使用多个Get方法进行路由
我正在使用ASP.NET MVC的Web Api,而且我对它很新颖。 我经历了一些在asp.net网站上的演示,我正在尝试做下面的事情。
我有4个get方法,具有以下签名
public List<Customer> Get() { // gets all customer } public List<Customer> GetCustomerByCurrentMonth() { // gets some customer on some logic } public Customer GetCustomerById(string id) { // gets a single customer using id } public Customer GetCustomerByUsername(string username) { // gets a single customer using username }
对于上面的所有方法,我想我的networkingapi有点像如下所示
- 列表Get()=
api/customers/
- Customer GetCustomerById(string Id)=
api/customers/13
- 列表GetCustomerByCurrentMonth()=
/customers/currentMonth
- Customer GetCustomerByUsername(string username)=
/customers/customerByUsername/yasser
我试图改变路由,但由于我是新来的,不能理解太多。
所以,请有人帮助我理解和指导我如何做到这一点。 谢谢
从这里路由在Asp.net Mvc 4和Web Api
Darin Dimitrov发布了一个非常好的答案,正在为我工作。
它说…
你可以有几条路线:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "ApiById", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: new { id = @"^[0-9]+$" } ); config.Routes.MapHttpRoute( name: "ApiByName", routeTemplate: "api/{controller}/{action}/{name}", defaults: null, constraints: new { name = @"^[az]+$" } ); config.Routes.MapHttpRoute( name: "ApiByAction", routeTemplate: "api/{controller}/{action}", defaults: new { action = "Get" } ); } }
首先,在顶部添加带有动作的新路线:
config.Routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
然后使用ActionName
属性来映射:
[HttpGet] public List<Customer> Get() { //gets all customer } [ActionName("CurrentMonth")] public List<Customer> GetCustomerByCurrentMonth() { //gets some customer on some logic } [ActionName("customerById")] public Customer GetCustomerById(string id) { //gets a single customer using id } [ActionName("customerByUsername")] public Customer GetCustomerByUsername(string username) { //gets a single customer using username }
只有一个足够的路线
config.Routes.MapHttpRoute("DefaultApiWithAction", "{controller}/{action}");
并且需要在所有动作中指定属性HttpGet或HttpPost 。
[HttpGet] public IEnumerable<object> TestGet1() { return new string[] { "value1", "value2" }; } [HttpGet] public IEnumerable<object> TestGet2() { return new string[] { "value3", "value4" }; }
你也将指定行动的路线设置路线
[HttpGet] [Route("api/customers/")] public List<Customer> Get() { //gets all customer logic } [HttpGet] [Route("api/customers/currentMonth")] public List<Customer> GetCustomerByCurrentMonth() { //gets some customer } [HttpGet] [Route("api/customers/{id}")] public Customer GetCustomerById(string id) { //gets a single customer by specified id } [HttpGet] [Route("api/customers/customerByUsername/{username}")] public Customer GetCustomerByUsername(string username) { //gets customer by its username }
您可能不需要对路由进行任何更改。 只需在您的customersController.cs文件中添加以下四个方法:
public ActionResult Index() { } public ActionResult currentMonth() { } public ActionResult customerById(int id) { } public ActionResult customerByUsername(string userName) { }
把相关的代码放在方法中。 使用提供的默认路由,您应该根据给定URL的操作和参数从控制器获取适当的操作结果。
修改您的默认路由为:
routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Api", action = "Index", id = UrlParameter.Optional } // Parameter defaults );
// this piece of code in the WebApiConfig.cs file or your custom bootstrap application class // define two types of routes 1. DefaultActionApi and 2. DefaultApi as below config.Routes.MapHttpRoute("DefaultActionApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }); config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { action = "Default", id = RouteParameter.Optional }); // decorate the controller action method with [ActionName("Default")] which need to invoked with below url // http://localhost:XXXXX/api/Demo/ -- will invoke the Get method of Demo controller // http://localhost:XXXXX/api/Demo/GetAll -- will invoke the GetAll method of Demo controller // http://localhost:XXXXX/api/Demo/GetById -- will invoke the GetById method of Demo controller // http://localhost:57870/api/Demo/CustomGetDetails -- will invoke the CustomGetDetails method of Demo controller // http://localhost:57870/api/Demo/DemoGet -- will invoke the DemoGet method of Demo controller public class DemoController : ApiController { // Mark the method with ActionName attribute (defined in MapRoutes) [ActionName("Default")] public HttpResponseMessage Get() { return Request.CreateResponse(HttpStatusCode.OK, "Get Method"); } public HttpResponseMessage GetAll() { return Request.CreateResponse(HttpStatusCode.OK, "GetAll Method"); } public HttpResponseMessage GetById() { return Request.CreateResponse(HttpStatusCode.OK, "Getby Id Method"); } //Custom Method name [HttpGet] public HttpResponseMessage DemoGet() { return Request.CreateResponse(HttpStatusCode.OK, "DemoGet Method"); } //Custom Method name [HttpGet] public HttpResponseMessage CustomGetDetails() { return Request.CreateResponse(HttpStatusCode.OK, "CustomGetDetails Method"); } }
我有两个相同或没有参数的get方法
[Route("api/ControllerName/FirstList")] [HttpGet] public IHttpActionResult FirstList() { } [Route("api/ControllerName/SecondList")] [HttpGet] public IHttpActionResult SecondList() { }
只需在AppStart=>WebApiConfig.cs
=>的register方法下定义自定义路由AppStart=>WebApiConfig.cs
config.Routes.MapHttpRoute( name: "GetFirstList", routeTemplate: "api/Controllername/FirstList" ); config.Routes.MapHttpRoute( name: "GetSecondList", routeTemplate: "api/Controllername/SecondList" );
最后我读了很多答案,我明白了。
首先,我在WebApiConfig.cs中添加了3个不同的路由
public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "ApiById", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: new { id = @"^[0-9]+$" } ); config.Routes.MapHttpRoute( name: "ApiByName", routeTemplate: "api/{controller}/{action}/{name}", defaults: null, constraints: new { name = @"^[az]+$" } ); config.Routes.MapHttpRoute( name: "ApiByAction", routeTemplate: "api/{controller}/{action}", defaults: new { action = "Get" } ); }
然后,从控制器function中删除ActionName,Route等。 所以基本上这是我的控制器。
// GET: api/Countries/5 [ResponseType(typeof(Countries))] //[ActionName("CountryById")] public async Task<IHttpActionResult> GetCountries(int id) { Countries countries = await db.Countries.FindAsync(id); if (countries == null) { return NotFound(); } return Ok(countries); } // GET: api/Countries/tur //[ResponseType(typeof(Countries))] ////[Route("api/CountriesByName/{anyString}")] ////[ActionName("CountriesByName")] //[HttpGet] [ResponseType(typeof(Countries))] //[ActionName("CountryByName")] public async Task<IHttpActionResult> GetCountriesByName(string name) { var countries = await db.Countries .Where(s=>s.Country.ToString().StartsWith(name)) .ToListAsync(); if (countries == null) { return NotFound(); } return Ok(countries); }
现在我可以运行以下的URL样本(名称和ID);
HTTP://本地主机:49787 / API /国家/ GetCountriesByName /法国
HTTP://本地主机:49787 / API /国家/ 1