This post explains in detail how to programmatically create a page in EPiServer CMS 5. It also shows how to publish a page through code, even when the current user lacks the necessary permissions.
1. Specify where to publish the page
Start off by deciding where you will publish your new page. This is accomplished by specifying a PageReference object pointing to the desired parent page, such as the start page in this example:
PageReference parent = PageReference.StartPage;
2. Create the new page
Next we are going to create a new empty page with default values according to the property settings of its page type. We do this by specifying the parent under which to create the page and by specifying the name of the page type to use:
PageData myPage = EPiServer.DataFactory.Instance.GetDefaultPageData(
parent,
"MyOwnPageType");
We now have an empty page under the specified parent page. Note that there are other overloads of the GetDefaultPageData method that can be used. Now we have to specify our page property values before publishing the page.
3. Set page property values
Now let's define some standard property values and some user-defined property values:
myPage.PageName = "My new page";
myPage.URLSegment = EPiServer.Web.UrlSegment.CreateUrlSegment(myPage);
Now we've set the page name and the URL segment (the URL after the host name of our website, such as 'www.mysite.com/parent-page/my-new-page').
Let's specify one of our user-defined properties as well:
newTagPage.Property["MainBody"].Value =
"<p>This is the content.</p>";
newTagPage.Property["Birthday"].Value =
new DateTime(1981,12,31);
4. Publish the page
Finally, we are going to publish our newly created page by calling the Save method of the DataFactory class:
DataFactory.Instance.Save(myPage,
EPiServer.DataAccess.SaveAction.Publish);
Note that this method call requires that the current user has the proper permissions to publish a page in this location. This may cause a problem if the current user is an anonymous user and you still want the page to be published programmatically.
To circumvent this, you may use another overload of the Save method to permit the publishing even though the current user does not have the necessary permissions:
DataFactory.Instance.Save(
myPage,
EPiServer.DataAccess.SaveAction.Publish,
EPiServer.Security.AccessLevel.NoAccess);
There you go! We have now created a new page and set its properties entirely through code. Sweet, huh?
Update: I've updated this post according to the comments below.
Update #2: Also check out my post on modifying existing pages in EPiServer.