Monday, May 23, 2016

Restful web services (Web API) with Sitecore

Use for pagination without page reload. There's three pieces to it:

1. Register the route via a pipeline processor

using Sitecore.Pipelines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace Sitecore.Feature.Business.Pipelines
{
  public class RegisterHttpRoutes
  {    public void Process(PipelineArgs args)
    {
      GlobalConfiguration.Configure(Configure);
    }

    protected void Configure(HttpConfiguration configuration)
    {
      var routes = configuration.Routes;
      routes.MapHttpRoute("PartnersApi", "api/partners/{id}", new
      {
        controller = "BusinessSearchApi",
        action = "Search"
      });
    }
  }

}

2. Create a controller with a POST method that returns results

using Sitecore.Feature.Business.Models;
using Sitecore.Foundation.Indexing.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace Sitecore.Feature.Business.Controllers
{
  public class BusinessSearchApiController : ApiController
  {
    [System.Web.Http.HttpPost]
    public ISearchResults Search(PartnerQuery query)
    {
      var result = new List<string>();

      //TODO: call search service

      return new SearchResults() { TotalNumberOfResults = 50 };
    }
  }
}

3. Use Postman to test the POST request. Browser only does GET requests. 

http://sitecore.local/api/partners/someId   returns

{
  "Results": null,
  "TotalNumberOfResults": 50,
  "Query": null
}


In the Body you can specify the type of the incoming data and pass that data as a payload. 







No comments:

Post a Comment