Skip to content

Instantly share code, notes, and snippets.

@idac73
Last active September 12, 2017 14:18
Show Gist options
  • Save idac73/d6028956bfb7ad529717b0dd08388c16 to your computer and use it in GitHub Desktop.
Save idac73/d6028956bfb7ad529717b0dd08388c16 to your computer and use it in GitHub Desktop.
Umbraco ASP.NET Web API 2 (C#) Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Umbraco.Core;
using Umbraco.Web;
namespace ProductInfoSPA.Controllers
{
// Define the initial path for the API.
// Check the WebApiConfig.cs file in this gist for how the {ext} parameter is handled to serve either JSON or XML
[RoutePrefix("api/v1/app/{ext}")]
public class ProductInfoAPIController : ApiController
{
// Set and secure an instance of the UmbracoHelper for use in the API request.
private readonly UmbracoHelper _umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
// Enable the action for the API call and the specific endpoint options.
[HttpGet]
[Route("product/{culture=en}/{launch_status=production}")]
public IEnumerable<ProductInfoAPI> ProductInfoAPI(string culture, string launch_status)
{
// Set up list variables to aggregate all the requested content that will be served.
var appList = new List<ProductInfoAPI>();
var productList = new List<Product>();
var documentList = new List<Document>();
var termList = new List<Term>();
// In order to request Umbraco dictionary items, content needs to be requested and captured in variables.
var umbracoDictionary = ApplicationContext.Current.Services.LocalizationService.GetDictionaryItemChildren(Guid.Parse("A-HASH-GOES-HERE"));
var languages = ApplicationContext.Current.Services.LocalizationService.GetAllLanguages();
// Set up varibles that will store authroed Umbraco content that will be iterated through.
IEnumerable<Umbraco.Core.Models.IPublishedContent> umbracoProducts;
IEnumerable<Umbraco.Core.Models.IPublishedContent> umbracoDocuments;
umbracoProducts = _umbracoHelper.TypedContentAtRoot().DescendantsOrSelf("app").Where(x => x.Name == "product").Where(x => x.Parent.Name.ToLower() == culture).DescendantsOrSelf("product");
umbracoDocuments = _umbracoHelper.TypedContentAtRoot().DescendantsOrSelf("app").Where(x => x.Name == "product").Where(x => x.Parent.Name.ToLower() == culture).DescendantsOrSelf("user-docs");
// Iterate through Umbraco content and filter according to API parameters and content attributes.
foreach (var item in umbracoProducts)
{
if (launch_status == "development" && (item.GetPropertyValue<string>("launchStatus").ToLower() == "development" || item.GetPropertyValue<string>("launchStatus").ToLower() == "staging"))
{
productList.Add(new Product
{
// Post-process authored content to ensure clean data output for the API while assigning it to class entities.
Product_name = System.Web.HttpUtility.JavaScriptStringEncode(item.GetPropertyValue<string>("productName").Trim()),
Product_id = item.GetPropertyValue<string>("productID"),
Launch_status = item.GetPropertyValue<string>("launchStatus").ToLower(),
Mobile_app_support = item.GetPropertyValue<string>("mobileAppSupport").ToLower(),
Product_family = item.GetPropertyValue<string>("productFamily"),
Product_image_url = System.Web.HttpUtility.JavaScriptStringEncode(item.GetPropertyValue<string>("productImageURL").Trim()),
Product_release_notes = System.Web.HttpUtility.JavaScriptStringEncode(item.GetPropertyValue<string>("productReleaseNotes").Trim()),
});
} else if (item.GetPropertyValue<string>("launchStatus").ToLower() == "production")
{
productList.Add(new Product
{
// Post-process authored content to ensure clean data output for the API while assigning it to class entities.
Product_name = System.Web.HttpUtility.JavaScriptStringEncode(item.GetPropertyValue<string>("productName").Trim()),
Product_id = item.GetPropertyValue<string>("productID"),
Launch_status = item.GetPropertyValue<string>("launchStatus").ToLower(),
Mobile_app_support = item.GetPropertyValue<string>("mobileAppSupport").ToLower(),
Product_family = item.GetPropertyValue<string>("productFamily"),
Product_image_url = System.Web.HttpUtility.JavaScriptStringEncode(item.GetPropertyValue<string>("productImageURL").Trim()),
Product_release_notes = System.Web.HttpUtility.JavaScriptStringEncode(item.GetPropertyValue<string>("productReleaseNotes").Trim()),
});
}
}
foreach (var item in umbracoDocuments)
{
documentList.Add(new Document
{
// Post-process authored content to ensure clean data output for the API while assigning it to class entities.
Document_title = System.Web.HttpUtility.JavaScriptStringEncode(item.GetPropertyValue<string>("documentTitle").Trim()),
Document_body = System.Web.HttpUtility.JavaScriptStringEncode(item.GetPropertyValue<string>("documentBody").Trim()),
Document_name = System.Web.HttpUtility.JavaScriptStringEncode(item.Name).Trim(),
});
}
foreach (var item in umbracoDictionary)
{
termList.Add(new Term
{
// Post-process authored content to ensure clean data output for the API while assigning it to class entities.
Key = item.ItemKey.Replace("ProductInfoAPI.", ""),
Value = System.Web.HttpUtility.JavaScriptStringEncode(item.Translations.Where(x => x.Language.CultureInfo.Name.ToLower() == culture).Select(x => x.Value).FirstOrDefault().Trim()),
});
}
// Aggreate results of iterating through content in preparation to be served.
appList.Add(new ProductInfoAPI
{
Locale = culture,
Products = productList,
Documents = documentList,
Dictionary = termList
});
// If any of the Umbraco content is missing / corrupted, return an empty node.
if (!umbracoProducts.Any() | !umbracoDocuments.Any() | !umbracoDictionary.Any())
{
return Enumerable.Empty<ProductInfoAPI>();
}
// Serve that data to the client
return appList;
}
}
// A container entity to define and capture the main components of the API endpoint
public class ProductInfoAPI
{
public string Locale { get; set; }
// Here's your challenge. Write the other class containers for Products, Documents and Dictionary
public List<Product> Products { get; set; }
public List<Document> Documents { get; set; }
public List<Term> Dictionary { get; set; }
}
}
using Newtonsoft.Json.Serialization;
using System.Net.Http.Formatting;
using System.Web.Http;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Format the JSON output for standards and best practices
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
// Allow API writers to include JSON as an output option parameter
config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
// Allow API writers to include XML as an output option parameter
config.Formatters.XmlFormatter.UseXmlSerializer = true;
config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");
config.MapHttpAttributeRoutes();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment