How to add custom methods to ASP.NET WebAPI controller?

DmitryBoyko picture DmitryBoyko · Jul 19, 2014 · Viewed 39k times · Source

In ASP.NET MVC WebAPI project by default we have created following controller

 public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
}

But is possible to add here any custom methods so they can support get/post as well?

Thank you!

Answer

Shawn Mclean picture Shawn Mclean · Jul 19, 2014

You can use attributes such as the RoutePrefix with the Http type.

[Route("ChangePassword")]
[HttpPost] // There are HttpGet, HttpPost, HttpPut, HttpDelete.
public async Task<IHttpActionResult> ChangePassword(ChangePasswordModel model)
{        
}

The http type will map it back to its correct method in combination with the Route name.