繁体   English   中英

从Umbraco中获取JSON数据

[英]Get JSON data out of Umbraco

我是一名前端开发人员,因此请原谅我缺乏解释我的问题的能力。

我正在尝试在Umbraco项目中创建一些页面,这些页面使用Vue.js显示数据。 为此,我尝试设置一个自定义API控制器,该控制器将在调用时返回我想要的数据。

一个简单的例子就是我要返回所有博客文章。 下面是我目前得到的代码:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Web; using System.Web.Http; using Umbraco.Web.WebApi; using Umbraco.Web.PublishedContentModels; using Newtonsoft.Json; namespace Controllers.WebAPI.Qwerty { [Route("api/[controller]")] public class PostsApiController : UmbracoApiController { [HttpGet] public string Test() { return "qwerty"; } } } 

我已经阅读了许多文章,但是似乎无法掌握查询Umbraco想要返回的数据所需做的事情?

我尝试添加

var content = Umbraco.TypedContent(1122);

然后返回该错误,但出现错误:

(local variable) Umbraco.Core.Models.IPublishedContent content
Cannot implicitly convert type 'Umbraco.Core.Models.IPublishedContent' to 'string'

然后,我尝试序列化var content但遇到了以下问题:

Self referencing loop detected for property 'FooterCtalink' with type 
'Umbraco.Web.PublishedContentModels.Blog'. Path 
'ContentSet[0].FeaturedProducts[0].Features[0].ContentSet[0]'.

任何帮助都太棒了!

编辑:

我尚未编辑控制器,如下所示:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Web; using Umbraco.Web.WebApi; using Umbraco.Web.PublishedContentModels; using Newtonsoft.Json; using System.Web.Mvc; using DTOs.PostDTO; namespace Controllers.WebAPI.Qwerty { [Route("api/[controller]")] public class PostsApiController : UmbracoApiController { [HttpGet] public PostDTO Test() { // 1. Get content from umbraco var content = Umbraco.TypedContent(1122); // 2. Create instance of your own DTO var myDTO = new PostDTO(); // 3. Pupulate your DTO myDTO.Url = content.Url; // 4. return it return myDTO; } } } 

并像这样创建了一个DTO:

 namespace DTOs.PostDTO { public class PostDTO { public string Url { get; set; } } } 

但是,当控制台在ajax请求之后记录我的数据时,我只得到1122

问题在于,您无法以循环方式在JSON中返回.NET对象。

要解决您的问题,您只需执行以下步骤:

  1. 创建自己的DTO并在其中添加必需的属性。
  2. 使用C#从Umbraco API提取内容并填充自定义DTO对象。
  3. 从JsonResult返回该DTO。

您的代码如下所示:

[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
    [HttpGet]
    public MyDTO Test()
    {
        // 1. Get content from umbraco
        var content = Umbraco.TypedContent(1122);

        // 2. Create instance of your own DTO
        var myDTO = new MyDTO();

        // 3. Pupulate your DTO
        myDTO.SomeProperty = content.SomeProperty;

        // 4. return it
        return myDTO;
    }
}

您走在正确的轨道上。

我认为您需要返回ActionResult而不是字符串。

就像是:

    [HttpGet]
    public ActionResult Test()
    {
        var content = Umbraco.TypedContent(1122);
        return new JsonResult(content);
    }

这应将umbraco对象返回为Json。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM