Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful Controllers with Different Http Methods, But the Same Parameters

Let's say I have a Controller that handles a CRUD scenario for a 'Home'. The Get would look something like this:

    [HttpGet]
    public ActionResult Index(int? homeId)
    {
        Home home = homeRepo.GetHome(homeId.Value);

        return Json(home, JsonRequestBehavior.AllowGet);
    }

So far so good. Then I add a post action for adding new ones.

    [HttpPost]
    public ActionResult Index(Home home)
    {
        //add the new home to the db

        return Json(new { success = true });
    }

Awesome. But when I use the same scheme to handle puts (updating an existing home)...

    [HttpPut]
    public ActionResult Index(Home home)
    {
        //update existing home in the db

        return Json(new { success = true });
    }

We run into a problem. The method signatures for Post and Put are identical, which of course C# doesn't like. I could try a few things, like adding bogus parameters to the signature, or changing the method names to directly reflect CRUD. Those are hacky or undesirable, though.

What is the best practice for going about preserving RESTful, CRUD style controllers here?

like image 439
Dusda Avatar asked Dec 16 '22 17:12

Dusda


1 Answers

This is the best solution that I know of:

[HttpPut]
[ActionName("Index")]
public ActionResult IndexPut(Home home) 
{
     ...
}

Basically the ActionNameAttribute was created to deal with these scenarios.

like image 192
Matt Greer Avatar answered Apr 27 '23 02:04

Matt Greer