Skip to content

Instantly share code, notes, and snippets.

@nathanwoulfe
Created March 15, 2022 21:34
Show Gist options
  • Save nathanwoulfe/d1eb0f3d93b491c64d33fff12e89c7de to your computer and use it in GitHub Desktop.
Save nathanwoulfe/d1eb0f3d93b491c64d33fff12e89c7de to your computer and use it in GitHub Desktop.
Change content type via reflection
public class ChangeContentTypeController : UmbracoAuthorizedApiController
{
private readonly IContentTypeService _contentTypeService;
private readonly IContentService _contentService;
public ChangeContentTypeController(IContentTypeService contentTypeService, IContentService contentService) {
_contentTypeService = contentTypeService;
_contentService = contentService;
}
[HttpGet]
public IHttpActionResult Convert(int nodeId, string newTypeAlias)
{
var newType = _contentTypeService.GetAll().FirstOrDefault(x => x.Alias == newTypeAlias);
if (newType == null)
return BadRequest("Could not find content type");
var originalContent = _contentService.GetById(nodeId);
if (originalContent.ContentType.Alias == newTypeAlias)
{
return BadRequest("node has already been converted");
}
Type thisType = originalContent.GetType();
MethodInfo changeContentType = thisType
.GetMethod("ChangeContentType",
types: new[] { typeof(IContentType) },
modifiers: null,
binder: null,
bindingAttr: BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
changeContentType.Invoke(originalContent, new[] { newType });
originalContent.TemplateId = newType.DefaultTemplate.Id;
_contentService.Save(originalContent);
return Ok();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment