Easy custom Sitecore MVC controllers

This post will be short and sweet. You’ve got a custom item editor or maybe you made a new page that’s accessed by the dashboard, or possibly you are making a custom control or new speak control and you need to add a controller to manage some logic for you. The following method works great for CM/master database only type customization.

Creating the controller

The only thing you really need to do is add the controller to your project. Sitecore will provide access to it. No route configuration needed, no pipeline processor to register any routes. Just add it to your solution. The path to it will be:

/api/sitecore/{controller}/{action}

Below is sample code for a controller.

using Newtonsoft.Json;
using SampleSite.Utilities;
using System.Linq;
using System.Web.Mvc;

namespace SampleSite.Controllers
{
    [Authorize]
    public class UsersController : Controller
    {
        Sitecore.Data.Database _database = null;
        public UsersController()
        {
            _database = Sitecore.Configuration.Factory.GetDatabase("master");
        }

        //Path:  /api/sitecore/users/list
        public ActionResult List()
        {
            var userNames = Sitecore.Security.Accounts.UserManager.GetUsers().Select(x => new { x.Profile.UserName, x.Profile.FullName, x.DisplayName }).ToList();
            return new JsonNetResult(userNames, Formatting.Indented);
        }

        //Path:  /api/sitecore/users/search
        public ActionResult Search(string term)
        {
            var userNames = Sitecore.Security.Accounts.UserManager.GetUsers().Where(x=>x.Profile.UserName.ToLower().Contains(term.ToLower())).Select(x => new { x.Profile.UserName, x.Profile.FullName, x.DisplayName }).ToList();
            return new JsonNetResult(userNames, Formatting.Indented);
        }       
    }
}

Securing the controller

Easy! Just put the Authorize attribute on the class or a method.

About Phil Paris

Hi, my name is Phil Paris and I’m a Sitecore Architect and general Sitecore enthusiast. I’ve been working with Sitecore since 2013. Through this blog I will be sharing Sitecore insights, tips and tricks, best practices and general knowledge with the hopes to further the community at large. Please feel free to reach out to me at any time!

View all posts by Phil Paris →