HomeDev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideLegal TermsGitHubNuGetDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Install version 5

Describes how to install and configure the Optimizely Service API version 5, a service layer used for integration of Optimizely Commerce with external systems, such as PIM, DAM and ERPs.

Prerequisites

Install Optimizely updates through the NuGet Package Manager in Visual Studio.

Install Service API

  1. Open Visual Studio.
  2. Right-click on the project and choose Properties.
  3. Set the target framework for your project to .NET Framework 4.6.1 or higher.
  4. Select Tools > NuGet Package Manager > Manage NuGet packages for Solution.... You can also right-click on the solution References and select there).
  5. Click Settings to create a source pointing to the Optimizely NuGet feed.
  6. Open the Online section and select the source you just created.
  7. Install EPiServer.ServiceApi or EPiServer.ServiceApi.Commerce if working with Commerce and all dependencies, including Optimizely and third-party packages.

    📘

    Note

    Ensure you install EPiServer.ServiceApi and EPiServer.ServiceApi.Commerce on the front-end site, not the Commerce Manager back-end site.

  8. Select Tools > NuGet Package Manager > Package Manage Console and run the command update-epidatabase to automatically set administrator permissions. Check that they are set correctly. Otherwise, set account permissions for administrators to execute the Service API in the database (tblUserPermission) to prevent returning an HTTP 401 status.
  9. Open EPiServerFramework.config and ensure that <appData> has a <basePath> directory pointing to a valid location with IIS write permissions. The EPiServerFramework.config file is at the same level as the web.config file. It can be <episerver.framework configSource="EPiServerFramework.config" >/ or <episerver.framework ...>< the settings> </episerver.framework>.

    📘

    Note

    Monitor this folder over time because there is no built-in cleanup.

  10. Open IIS > Edit Bindings and assign a custom HTTPS binding. HTTPS is required for the integration service.
  11. Open the website to verify that it works.

Configure OWIN startup

Because Service API uses OWIN-based authentication, configure this in the application’s Startup class.

📘

Note

The Startup class should be in the web app's root folder; see OWIN Startup Class Detection .

The EPiServer.ServiceApi.Owin namespace contains the application builder extension methods for this configuration. The following example sets up Service API to authenticate service calls using ASP.NET Membership.

using EPiServer.ServiceApi.Owin;
using Owin;

namespace EPiServer.ServiceApi.Sample
  {
    public class Startup
      {
        public void Configuration(IAppBuilder app)
          {
            // Enable bearer token authentication using Membership for Service Api
            app.UseServiceApiMembershipTokenAuthorization();
          }        
      }
  }

You can also set Service API to authenticate service calls using ASP.NET Identity . The following example extends the Optimizely UI ASP.NET call to the UseServiceApiIdentityTokenAuthorization method to configure Service API to use the same user type.

using System;
using EPiServer.Cms.UI.AspNetIdentity;
using EPiServer.ServiceApi.Owin;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

namespace EPiServer.ServiceApi.Sample
  {
    public class Startup
      {
        public void Configuration(IAppBuilder app)
          {
            // Add CMS integration for ASP.NET Identity
            app.AddCmsAspNetIdentity<ApplicationUser>();

            // Use cookie authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions
              {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/util/login.aspx"),
                Provider = new CookieAuthenticationProvider
                  {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager<ApplicationUser>,
                                         ApplicationUser>(
                                                           validateInterval   : TimeSpan.FromMinutes(30),
                                                           regenerateIdentity : (manager, user) => 
                                                             manager.GenerateUserIdentityAsync(user)
                                                         )
                  }
              });

            // Enable bearer token authentication using ASP.NET Identity for Service Api
            app.UseServiceApiIdentityTokenAuthorization<ApplicationUserManager<ApplicationUser>, ApplicationUser>();
          }
      }
  }

📘

Note

Ensure you have a registered user account with appropriate permissions (Administrators member). Because the Service API uses the authorization provider specified in the Startup file, replace other uses of authorization server like UseOAuthAuthorizationServer with IAppBuilder.UseServiceApiIdentityTokenAuthorization.

Configuration modifications

Some settings are configured in the OWIN startup, while others are configured in web.config.

Token timeout in minutes

You can add this setting to the OWIN startup configuration. If omitted, the default OAuthAuthorizationServerOptions.AccessTokenExpireTimeSpan is used (20 minutes).

app.UseServiceApiMembershipTokenAuthorization(new ServiceApiTokenAuthorizationOptions
  {
    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60)
  });

File upload maximum size

To increase the maximum size that can be uploaded, change maxAllowedContentLength. The maximum file size is 2 GB.

📘

Note

maxAllowedContentLength is in bytes, while maxRequestLength is in kilobytes.

<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="524288000" />
    </requestFiltering>
  </security>
</system.webServer>
<system.web>
  <httpRuntime requestValidationMode="2.0" maxRequestLength="102400" />
</system.web>

Disable attribute routing

XMLService API automatically enables attribute routing. If you already configured this, you can disable the Service API from automatically enabling attributes by adding an app setting, see Attribute Routing in ASP.NET Web API 2 .

<appsettings>
  <add key="episerver:serviceapi:maphttpattributeroutes" value="false" />
</appsettings>

Disable SSL requirement for request

By default, Service API requires secure connections for authentication and API calls. You can disable this with an app setting, such as for a debug configuration in development.

<appsettings>
  <add key="episerver:serviceapi:requiressl" value="false" />
</appsettings>

📘

Note

Live sites should not disable SSL.

Authentication tokens

To use any EPiServer.ServiceApi RESTful method, obtain an OAuth 2 Bearer Token to send with the request.

using (var client = new HttpClient())
  {
    client.BaseAddress = new Uri("https://mysite.com/");
    var fields = new Dictionary<string, string>
      {
        { "grant_type", "password" },
        { "username", username },
        { "password", password }
      };
    var response = client.PostAsync("/episerverapi/token", new FormUrlEncodedContent(fields)).Result;
    if (response.StatusCode == HttpStatusCode.OK)
      {
        var content = response.Content.ReadAsStringAsync().Result;
        var token = JObject.Parse(content).GetValue("access_token");
      }
  }			

POST /episerverapi/token HTTP/1.1
Host: mysite.com
User-Agent: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant_type=password
username=test
password=test
HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140
{"token_type":"bearer","access_token":"AAAA%2FAAA%3DAAAAAAAA"}

Send request with tokens

using (var client = new HttpClient())
  {
    client.BaseAddress = new Uri("https://mysite.com/");
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString());
    var content = new MultipartFormDataContent();
    var filestream = new FileStream(path, FileMode.Open);
    content.Add(new StreamContent(filestream), "file", "Catalog.zip");
    var response = client.PostAsync("/episerverapi/commerce/import/catalog", content).Result;
    if (response.StatusCode == HttpStatusCode.OK)
      {
        var returnString = response.Content.ReadAsStringAsync().Result;
        returnString = returnString.Replace("\"", "");
        Guid taskId = Guid.Empty;
        Guid.TryParse(returnString, out taskId);
      }
  }

Strongly typed catalog content types

Strongly typed catalog content types must be present in the context of a ServiceAPI site. If you install ServiceAPI to an existing website, this is solved automatically. However, if you install ServiceAPI as a standalone application, you must deploy the assembly that contains strongly typed catalog content types (and any dependencies of your assembly) to the ServiceAPI bin folder.

Troubleshoot

The following issues may arise when you set up the Service API.

  • You should ensure there is a valid certificate on the server from a trusted certificate authority for the site.
  • All Service API requests must be HTTPS.
  • You receive an error when sending a file to an import method. The Service API stores uploaded files in the AppDataPath set in the episerverframework.config file. Ensure the specified folder has the proper security permissions for the application pool identity.
  • You must have a proper OWIN startup. If there is a key in the app settings, you can disable this.
    <add key="owin:AutomaticAppStartup" value="false" />
  • If controller resolution appears not to be working correctly, delete the temporary ASP.NET files and see if that fixes the problem.