Steve
Steve

Reputation: 4513

Custom method for Web API which is not standard CRUD methods

I notice that most of the web api tutorial just mention the CRUD methods. My question is what about those method which is not CRUD? Example, if I have a model for Employee with these following properties: Id, Name, Email, Username and Password. For the admin module, for update employee function, there is no problem because the web api will be in CRUD. For example below:

public class EmployeeController : ApiController
{
    private AppDbContext db = new AppDbContext();

// PUT api/Employee/5
    public IHttpActionResult PutEmployee(int id, Employee employee)
    {

        if (id != employee.EmployeeID)
        {
            return BadRequest();
        }

        db.Entry(employee).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!EmployeeExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }
}

But for employee module, what about change password function? Do I need to create another controller with put verb just for each function?

I found an article which is related to my question. How do I create a custom method like deposit (httppost) and witdrawal (httppost) for an ATM program?

Upvotes: 0

Views: 270

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26432

It depends on the situation. If you feel that the password is a resource of itself, then you can have the following:

PUT api/customer/{id}/password

That would become in your controller

public IHttpActionResult PutCustomerPassword(int id, Password password)

If the password is just a string in Customer, then update the Customer sendind the new password in the Employee object.

You can ofcourse use inheritance, creating a new base Controller, that has some user management functionality and share between the Employee and the Customer. This way you can use the CustomerController and EmployeeController just as an entry point and call the BaseController code to do the actual work.

Upvotes: 1

Related Questions