Маршрутизация с несколькими методами Get в ASP.NET Web API
я использую веб-Api с ASP.NET MVC, и я очень новичок в этом. Я прошел через некоторые демо на 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
}
для всех методов выше я хотел бы иметь свой веб-api, как показано ниже
- List Get() =
api/customers/
- Customer GetCustomerById (string Id) =
api/customers/13
- список GetCustomerByCurrentMonth ()=
/customers/currentMonth
- Customer GetCustomerByUsername (string username) =
/customers/customerByUsername/yasser
Я попытался внести изменения в маршрутизацию, но, поскольку я новичок в этом, не мог понять многого.
Итак, пожалуйста, может кто-нибудь помочь мне понять и направить меня на то, как это должно быть сделано. Спасибо
10 ответов:
отсюда маршрутизация внутри Asp.net Mvc 4 и Web Api
Дарин Димитров выложил очень хороший ответ, который работает для меня.
Он говорит...
вы могли бы иметь несколько маршрутов:
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 = @"^[a-z]+$" } ); 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 } );затем использовать на карте:
[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 }
также нужно будет указать маршрут на действия по заданному маршруту
[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 }
только один маршрут достаточно для этого
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" }; }
есть много хороших ответов уже на этот вопрос. Однако в настоящее время конфигурация маршрута является своего рода "устаревшей". Более новая версия MVC (.NET Core) не поддерживает его. Так что лучше к нему привыкнуть:)
поэтому я согласен со всеми ответами, которые используют маршрутизацию стиля атрибута. Но я все время замечаю, что все повторили базовую часть маршрута (api/...). Лучше применить [RoutePrefix] атрибут поверх класса контроллера и не повторяйте одна и та же строка снова и снова.
[RoutePrefix("api/customers")] public class MyController : Controller { [HttpGet] public List<Customer> Get() { //gets all customer logic } [HttpGet] [Route("currentMonth")] public List<Customer> GetCustomerByCurrentMonth() { //gets some customer } [HttpGet] [Route("{id}")] public Customer GetCustomerById(string id) { //gets a single customer by specified id } [HttpGet] [Route("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= > в разделе метод регистрацииconfig.Routes.MapHttpRoute( name: "GetFirstList", routeTemplate: "api/Controllername/FirstList" ); config.Routes.MapHttpRoute( name: "GetSecondList", routeTemplate: "api/Controllername/SecondList" );
после прочтения много ответов, наконец, я понял.
во-первых, я добавил 3 различных маршрута в WebApiConfig.cs
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 = @"^[a-z]+$" } ); config.Routes.MapHttpRoute( name: "ApiByAction", routeTemplate: "api/{controller}/{action}", defaults: new { action = "Get" } ); }затем удаляется имя действия, маршрут и т. д.. от функций контроллера. Так что в основном это мой контроллер;
// 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 (с именем и с помощью идентификатор);
http://localhost:49787/api/Countries/GetCountriesByName/France
using Routing.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Routing.Controllers { public class StudentsController : ApiController { static List<Students> Lststudents = new List<Students>() { new Students { id=1, name="kim" }, new Students { id=2, name="aman" }, new Students { id=3, name="shikha" }, new Students { id=4, name="ria" } }; [HttpGet] public IEnumerable<Students> getlist() { return Lststudents; } [HttpGet] public Students getcurrentstudent(int id) { return Lststudents.FirstOrDefault(e => e.id == id); } [HttpGet] [Route("api/Students/{id}/course")] public IEnumerable<string> getcurrentCourse(int id) { if (id == 1) return new List<string>() { "emgili", "hindi", "pun" }; if (id == 2) return new List<string>() { "math" }; if (id == 3) return new List<string>() { "c#", "webapi" }; else return new List<string>() { }; } [HttpGet] [Route("api/students/{id}/{name}")] public IEnumerable<Students> getlist(int id, string name) { return Lststudents.Where(e => e.id == id && e.name == name).ToList(); } [HttpGet] public IEnumerable<string> getlistcourse(int id, string name) { if (id == 1 && name == "kim") return new List<string>() { "emgili", "hindi", "pun" }; if (id == 2 && name == "aman") return new List<string>() { "math" }; else return new List<string>() { "no data" }; } } }
Comments