无法使用 ContentService 中的 SaveAndPublish

Unable to use SaveAndPublish from ContentService

我正在尝试保存名为 childIContent,但是在这一行 (contentService.SaveAndPublish(child);) 上我收到以下错误:Object reference not set to an instance of an object.

if (child.HasProperty("navn"))
{
    child.SetValue("navn", worker.Name.ToString(), "da-dk");
}
contentService.SaveAndPublish(child);

这就是我定义 contentService 的方式:
IContentService contentService = Umbraco.Core.Composing.Current.Services.ContentService;

我发现 children 是这样的:

long totalChildren;

IEnumerable<IContent> children = contentService.GetPagedChildren(filialsParent.Id, 0, 100, out totalChildren);

´ 有人可以指出这里有什么问题吗?

我认为您获取 ContentService 的方式有误,因此它可能为空,从而导致空引用异常。

如果你在 SurfaceController 中,你可以像这样获取 ContentService:

var cs = Services.ContentService;

如果您处于未公开服务的 class 中,您可以这样获取它:

var cs = ApplicationContext.Current.Services.ContentService;

在下面的 Umbracos 文档中阅读更多相关信息:)

https://our.umbraco.com/documentation/Reference/Management/Services/ContentService/

that link,似乎 Umbraco 'Save' 即使某些内容为 null 但不完全为 null 也能工作:

Save is working but not completely, it is saving the content to the db but not to the Umbraco backoffice. And even when I try wrapping the setValues inside a

if (blogNode.HasProperty("title")) {

I still get a null reference error.

在 OP 案例中,他在第一步中采用了错误的 contentService,所以我认为@Mikkel 的回答并非完全错误:

Turns out I had used the wrong parentId in this line:

var newBlog = contentService.CreateContent(post.Title, 1053, "umbNewsItem", 0);

the correct statement was:

var newBlog = contentService.CreateContent(post.Title, 1061, "umbNewsItem", 0);

L-

我发现如果我这样做就可以了。

var umbf = Umbraco.Web.Composing.Current.Factory.GetInstance<IUmbracoContextFactory>();
using (var contextf = umbf.EnsureUmbracoContext())
{
    var umbcontext = contextf.UmbracoContext;
    IContentService cs = Umbraco.Core.Composing.Current.Services.ContentService;
    cs.SaveAndPublish(child);

}