简体   繁体   中英

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?

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

Used Action Name attribute

       [ActionName("Get")]
       public IEnumerable<Process_Settings> Get1()//used any name here
       {
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM