Created
March 15, 2022 21:34
-
-
Save nathanwoulfe/d1eb0f3d93b491c64d33fff12e89c7de to your computer and use it in GitHub Desktop.
Change content type via reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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