Routing with multiple Get methods in ASP.NET Web API

前端 未结 10 715
闹比i
闹比i 2020-11-27 10:13

I am using Web Api with ASP.NET MVC, and I am very new to it. I have gone through some demo on asp.net website and I am trying to do the following.

I have 4 get meth

相关标签:
10条回答
  • 2020-11-27 10:43

    After reading lots of answers finally I figured out.

    First, I added 3 different routes into 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" }
        );
    }
    

    Then, removed ActionName, Route, etc.. from the controller functions. So basically this is my controller;

    // 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);
    }
    

    Now I am able to run with following url samples(with name and with id);

    http://localhost:49787/api/Countries/GetCountriesByName/France

    http://localhost:49787/api/Countries/1

    0 讨论(0)
  • 2020-11-27 10:45

    There are lots of good answers already for this question. However nowadays Route configuration is sort of "deprecated". The newer version of MVC (.NET Core) does not support it. So better to get use to it :)

    So I agree with all the answers which uses Attribute style routing. But I keep noticing that everyone repeated the base part of the route (api/...). It is better to apply a [RoutePrefix] attribute on top of the Controller class and don't repeat the same string over and over again.

    [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
     }
    }
    
    0 讨论(0)
  • 2020-11-27 10:46

    First, add new route with action on top:

      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 }
            );
    

    Then use ActionName attribute to map:

    [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
    }
    
    0 讨论(0)
  • 2020-11-27 10:46

    Only one route enough for this

    config.Routes.MapHttpRoute("DefaultApiWithAction", "{controller}/{action}");
    

    And need to specify attribute HttpGet or HttpPost in all actions.

    [HttpGet]
    public IEnumerable<object> TestGet1()
    {
        return new string[] { "value1", "value2" };
    }
    
    [HttpGet]
    public IEnumerable<object> TestGet2()
    {
        return new string[] { "value3", "value4" };
    }
    
    0 讨论(0)
  • 2020-11-27 10:52

    You might not need to make any change in the routing. Just add following four methods in your customersController.cs file:

    public ActionResult Index()
    {
    }
    
    public ActionResult currentMonth()
    {
    }
    
    public ActionResult customerById(int id)
    {
    }
    
    
    public ActionResult customerByUsername(string userName)
    {
    }
    

    Put the relevant code in the method. With the default routing supplied, you should get appropriate action result from the controller based on the action and parameters for your given urls.

    Modify your default route as:

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Api", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
    
    0 讨论(0)
  • 2020-11-27 10:52
      // 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");
        }
    }
    
    0 讨论(0)
提交回复
热议问题