Search code examples
c#asp.net-mvcapiumbracoumbraco7

Sending The Content of a Document Type Via UmbracoApiController


How Can i OutPut the published Content of a Certain Document Type via Web Api?

Example: I have a Document Type Called

Comment

its has three Properties "Name, Date, Text" I Want To output the Values of those Properties to a UmbracoApiController So that I can Use it in other WebSites any thoughts ? Thanks in Advance

 public class  publishedContentapiController  : UmbracoApiController
{
    //What Logic To Put Here In Order to get the Content OF published 
   // Document Types With the Alias "comment" 
}

Solution

  • The below code outputs all documents of type "comment" through the webapi

    public class  publishedContentapiController  : UmbracoApiController
    {
        public IHttpActionResult GetComments()
        {
            // Create an UmbracoHelper for retrieving published content
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
    
            // Get all comments from the Umbraco tree (this is not a optimized way of doing this, since it queries the complete Umbraco tree)
            var comments = umbracoHelper.TypedContentAtRoot().DescendantsOrSelf("comment");     
    
            // Map the found nodes from IPublishedContent to a strongly typed object of type Comment (defined below)
            var mappedComments = comments.Select(x => new Comment{
                Name = x.Name,                              // Map name of the document
                Date = x.CreatedTime,                       // Map createdtime
                Text = x.GetPropertyValue<string>("text")   // Map custom property "text"
            });
    
            return Ok(mappedComments);
        }
    
    
        private class Comment
        {
            public string Name { get; set; }
            public DateTime Date { get; set; }
            public string Text { get; set; }
        }
    }
    

    Diclaimer: Code is untested and obviously needs refactoring