RESTful controllers with different Http methods but same parameters

Say I have a controller that processes a CRUD script for a "home". Get will 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 to add new ones.

  [HttpPost] public ActionResult Index(Home home) { //add the new home to the db return Json(new { success = true }); } 

Tall. 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 are facing a problem. The method signatures for Post and Put are identical, which, of course, C # does not like. I could try several things, for example add dummy parameters to the signature or change the names of methods to directly reflect CRUD. However, they are hacks or unwanted.

What is the best practice for keeping RESTful, CRUD style controllers here?

+4
source share
2 answers

This is the best solution I know of:

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

Basically, an ActionNameAttribute was created to address these scenarios.

+12
source

HttpPut and HttpDeletes are limited to some firewalls, so HttpPost and HttpGet are used from time to time. If the record identifier is passed (or some other criteria), you know its update. Granted - this is for you to determine if httpput may work just fine for you, this is just a warning about this, it is usually not very important.

Any method used - beware of users trying to enter false identifiers on a page to force updates to entries that they don’t have access to. I will get around this problem by hashing in this case home.HomeId in the view when we render it

  ViewData ["IdCheck"] = Encryption.ComputeHash (home.HomeId.ToString ());

In your opinion:

  <%: Html.Hidden ("IdCheck", ViewData ["IdCheck"])%>

in your HttpPost or HttpPut method (depending on what the update does)

  if (Encryption.ComputeHash (home.HomeId.ToString ())! = (string) Request.Form ["IdCheck"])
  {
        throw new Exception ("Hashes do not match");
 }

Again - the same security issue exists no matter what method you use to update, if you trust the form data.

0
source

Source: https://habr.com/ru/post/1338949/


All Articles