我是一名前端开发人员,因此请原谅我缺乏解释我的问题的能力。
我正在尝试在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对象。
要解决您的问题,您只需执行以下步骤:
创建自己的DTO并在其中添加必需的属性。
使用C#从Umbraco API提取内容并填充自定义DTO对象。
从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;
}
}