Search code examples
c#apirequestput

Is it possible to use custom API method name to allow multiple PUT methods in single API controller


firstly I can get around this issue by creating multiple API controllers in my web application. However, I wondered if it is possible to do the following:

I am trying to have two PUT methods in my API controller and just attempt to call them by api//Method-name/id using POSTMAN, I cannot get a response however when using what I assume would be the route for the HTTP put request. I have done some research and I'm not sure if this is possible or if the information is too outdated but I have found some information linking to a need of adding some routing code to my web application config? But I don't know the correct way to put this in the startup.cs file as there do not seem to be methods for Mapping HTTP routes?

Below is my code: Please note I'm not sure what other detail to add other than the controller and the POSTMAN url im trying (https://MY.I.P:44388/api/Data/Reject/1143) please let me know if I require more.

public class DataController : ControllerBase
{
    // PUT api/<DataController>/Accept
    [HttpPut("{id}")]
    public void Accept(int id)
    {
        try
        {
            using (RecoDBEntities Entities = new RecoDBEntities())
            {
                List<recovery_jobs> entity = new List<recovery_jobs>();
                entity = Entities.recovery_jobs.Where(e => e.DOCKETNO.ToString().Trim() == id.ToString().Trim()).ToList();
                recovery_jobs job = entity[0];
                job.STATUS = "ONROUTE";
                Entities.SaveChanges();
            }
        }
        catch (System.Exception)
        {

            throw;
        }  
    }

    // PUT api/<DataController>/Reject
    [HttpPut("{id}")]
    public void Reject(int id)
    {
        try
        {
            using (RecoDBEntities Entities = new RecoDBEntities())
            {
                List<recovery_jobs> entity = new List<recovery_jobs>();
                entity = Entities.recovery_jobs.Where(e => e.DOCKETNO.ToString().Trim() == id.ToString().Trim()).ToList();
                recovery_jobs job = entity[0];
                job.STATUS = "REJECTED";
                Entities.SaveChanges();
            }
        }
        catch (System.Exception)
        {

            throw;
        }
    }

    // DELETE api/<DataController>/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

The error I receive in POSTMAN is a 404


Solution

  • Moving comment to answer:

    Not by method name alone but you can do it by the route parameter. E.g.

    [Route(“accept/{id})]

    Also, as mentioned by Dan, you should still use the HttpPut attribute along with this.