Skip to content

Instantly share code, notes, and snippets.

@biapar
Last active September 22, 2022 13:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biapar/e48bb57e86759c9ffb14fdabbf804369 to your computer and use it in GitHub Desktop.
Save biapar/e48bb57e86759c9ffb14fdabbf804369 to your computer and use it in GitHub Desktop.
Piranha CMS: example of a simple controller to GET data in JSON format for headless use.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Piranha;
using Piranha.AspNetCore.Services;
using Piranha.Models;
using PiranhaCMS.Models;
using Microsoft.AspNetCore.Authorization;
namespace PiranhaCMS.Controllers
{
//[ApiController]
[Route("api/head")]
//[Authorize(Policy = Permissions.Pages)]
public class ApiLessController : Controller
{
private readonly IApi _api;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="app">The current app</param>
public ApiLessController(IApi api)
{
_api = api;
}
/// <summary>
/// Gets the blog archive with the given id.
/// </summary>
[Route("jsonarchive")]
public async Task<IActionResult> Archive(Guid id, int? year = null, int? month = null, int? page = null,
Guid? category = null, Guid? tag = null)
{
//GetByIdAsync<Models.StandardPost>(id);
var model = await _api.Pages.GetByIdAsync<Models.StandardArchive>(id);
//model.Archive = await _api.Archives.GetByIdAsync(id, page, category, tag, year, month);
return Json(model);
}
/// <summary>
/// Gets the page with the given id.
/// </summary>
[Route("jsonpage")]
public async Task<IActionResult> Page(Guid id)
{
var model = await _api.Pages.GetByIdAsync<PageBase>(id);
return Json(model);
}
/// <summary>
/// Gets the restricted page with the given id.
/// </summary>
/// <param name="id">The unique page id</param>
/// For security read: https://piranhacms.org/blog/techniques-for-securing-pages
[Route("jsonpagerestricted")]
//[Authorize(Policy = ...)]
public async Task<IActionResult> PageRestricted(Guid id)
{
var model = await _api.Pages.GetByIdAsync<PageBase>(id);
return Json(model);
}
/// <summary>
/// Gets the post with the given id.
/// </summary>
/// <param name="id">The unique post id</param>
///
[Route("jsonpost")]
public async Task<IActionResult> Post(Guid id)
{
var model = await _api.Posts.GetByIdAsync<PostBase>(id);
return Json(model);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment