Search code examples
c#asp.net-mvc-5asp.net-web-api2asp.net-web-api-routing

How to put multiple GET methods in Web API2 controller?


I am doing a Web API 2 application and I have controller named NCT_ProcessSettings and already I have two GET methods as below.

1. public IEnumerable<Process_Settings> Get()
2. public HttpResponseMessage Get(int id)

Now I want to have third one as below (Same as first one but inside I will write different logic).

3. public IEnumerable<Process_Settings> Get() //Compiler will confuse which to pick?

I tried as below.

[HttpGet]
[Route("GetGlobalSettings")]
public IEnumerable<NCT_Process_Settings> GetGlobalSettings()
{
    return entityObject.NCT_Process_Settings.Where(c => c.project_id == 0).ToList();
}

Below is my angularcode to call api.

 var url = '/api/NCT_ProcessSettings/GetGlobalSettings';

May I have some idea how to fix this? Any help would be appreciated?


Solution

  • Enable attribute routing in WebApiConfig.cs before convention-based routes.

    config.MapHttpAttributeRoutes();
    

    Next update controller to use routing attributes. (note the route prefix)

    [RoutePrefix("api/NCT_ProcessSettings")]
    public class NCT_ProcessSettingsController : ApiController {
    
        //GET api/NCT_ProcessSettings
        [HttpGet]
        [Route("")]
        public IEnumerable<Process_Settings> Get() { ... }
    
        //GET api/NCT_ProcessSettings/5
        [HttpGet]
        [Route("{id:int}")]
        public HttpResponseMessage Get(int id) { ... }
    
        //GET api/NCT_ProcessSettings/GetGlobalSettings
        [HttpGet]
        [Route("GetGlobalSettings")]
        public IEnumerable<NCT_Process_Settings> GetGlobalSettings() { ... }
    
    }
    

    Read up more documentation here Attribute Routing in ASP.NET Web API 2