crudumbracosurface-controllerumbraco-10

Can I create all CRUD Operations in a Surface Controller in Umbraco?


So I was wondering if it is possible to use a Surface Controller for all crud operations (Umbraco V10). I know that I can create a Post method, but is it possible to add a Delete or Patch method?

I tried to add a method like this:

public class DeleteController : SurfaceController {
    [HttpDelete]
    public IActionResult Delete()
    {
        ...
    }
}

but I only receive an 405 error telling me that the method is not allowed. If I change the [HttpDelet] to [HttpPost] the method works, but I think that is semantically not correct if i delete content in a POST method.

And am I correct in saying that it is not common to have multiple methods in one Surface Controller? So I would have to create a Controller for each method.


Solution

  • You should be able to use your Surface Controller for different CRUD operations. Below is a sample code from the Umbraco CMS document.

    Please take a look at this guide for more details.

    Here is another old but useful approach.

    PS: The attribute issue that you see could be a bug.You can check the existing Umbraco CMS issues here.

        namespace RoutingDocs.Controllers;
        ​
        public class MyController : SurfaceController
        {
            public MyController(
                IUmbracoContextAccessor umbracoContextAccessor,
                IUmbracoDatabaseFactory databaseFactory,
                ServiceContext services,
                AppCaches appCaches,
                IProfilingLogger profilingLogger,
                IPublishedUrlProvider publishedUrlProvider)
                : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider)
            {
            }
        ​
            [HttpPost]
            [ValidateUmbracoFormRouteString]
            public IActionResult HandleSubmitMethod1()
            {
                return RedirectToCurrentUmbracoPage();
            }
    
            [HttpPost]
            [ValidateUmbracoFormRouteString]
            public IActionResult HandleSubmitMethod2()
            {
               return Content("Hello Postback");
            }
        }