Issue when setting up ASP .NET CORE app with Kentico on IIS

Francis Carroll asked on February 14, 2022 12:19

Hi,

I am running an ASP .NET CORE App v3.1 with Kentico 13 on a IIS 10 Windows Server.

I have this app setup on a local IIS server and it works perfectly but when I put it onto the server the front end and the Edit/Preview of the admin site wont load. We also tested this with the dancing goat site and the front end also wont display but the Edit/Preview does.

I have installed the 3.1.0 windows .NET Core hosting bundle on the server and enabled the relevant windows features.

As a test I set up a small test project with .NET Core to see if it would work on the server and it worked fine.

Here are the errors and warnings on the Event viewer of the server. Warnings:

Level   Date and Time   Source  Event ID    Task Category
Warning 14/02/2022 10:18:36 .NET Runtime    1000    None    "Category: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager
EventId: 35

No XML encryptor configured. Key {9e10d3c5-61aa-4a20-b8fe-4922c789ce6b} may be persisted to storage in unencrypted form.
"
Warning 14/02/2022 10:18:36 .NET Runtime    1000    None    "Category: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager
EventId: 59

Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.
"
Warning 14/02/2022 10:18:36 .NET Runtime    1000    None    "Category: Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository
EventId: 50

Using an in-memory repository. Keys will not be persisted to storage.
"

Errors:

Level   Date and Time   Source  Event ID    Task Category
Error   14/02/2022 09:58:08 Microsoft-Windows-DistributedCOM    10016   None    "The application-specific permission settings do not grant Local Activation permission for the COM Server application with CLSID 
{D63B10C5-BB46-4990-A94F-E40B9D520160}
 and APPID 
{9CA88EE3-ACB7-47C8-AFC4-AB702511C276}
 to the user Window Manager\DWM-2 SID (S-1-5-90-0-2) from address LocalHost (Using LRPC) running in the application container Unavailable SID (Unavailable). This security permission can be modified using the Component Services administrative tool."

Startup.cs

public class Startup
{
        private const string CONSTRAINT_FOR_NON_ROUTER_PAGE_CONTROLLERS = "SmartSearch";

        public IWebHostEnvironment Environment { get; }

        public IConfiguration Configuration { get; }

        public IContainer ApplicationContainer { get; private set; }

        public AutoFacConfig AutoFacConfig => new AutoFacConfig();


        public Startup(IWebHostEnvironment environment, IConfiguration configuration)
        {
            Environment = environment;
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddDbContext<DBContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("HorseRacingDataConnectionString")));

                services.AddDbContext<RacingColoursDBContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("ReportingDataConnectionString")));
            }
            catch (Exception ex)
            {
                throw (ex);
            }

            //used for send data using ajax because razor has anti-forgery texts built in
            services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

            //Used for recieving data from ajax call
            services.Configure<IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
                options.AutomaticAuthentication = false;
            });

            services.AddSingleton<DB>();

            // Enable desired Kentico Xperience features
            var kenticoServiceCollection = services.AddKentico(features =>
            {
                features.UsePageBuilder();
                features.UsePageRouting(new PageRoutingOptions
                {
                    EnableAlternativeUrls = true,
                    CultureCodeRouteValuesKey = "culture"
                });
            })
            .SetAdminCookiesSameSiteNone();

            services.Configure<KenticoRequestLocalizationOptions>(options =>
            {
                options.RequestCultureProviders.Add(new RouteDataRequestCultureProvider
                {
                    RouteDataStringKey = "culture",
                    UIRouteDataStringKey = "culture"
                });
            });

            if (Environment.IsDevelopment())
            {
                kenticoServiceCollection.DisableVirtualContextSecurityForLocalhost();
            }

            services.AddControllersWithViews();
        }

        /// <summary>
        /// Registers a handler in case Xperience is not initialized yet.
        /// </summary>
        /// <param name="builder">Container builder.</param>
        private void RegisterInitializationHandler(ContainerBuilder builder) =>
            CMS.Base.ApplicationEvents.Initialized.Execute += (sender, eventArgs) => AutoFacConfig.ConfigureContainer(builder);

        public void ConfigureContainer(ContainerBuilder builder)
        {
            try
            {
                AutoFacConfig.ConfigureContainer(builder);
            }
            catch
            {
                RegisterInitializationHandler(builder);
            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseStaticFiles();

            app.UseKentico();

            app.UseCookiePolicy();
            app.UseCors();

            app.UseEndpoints(endpoints =>
            {
                endpoints.Kentico().MapRoutes();

                endpoints.MapControllerRoute(
                   name: "error",
                   pattern: "error/{code}",
                   defaults: new { controller = "HttpErrors", action = "Error" }
                );

                endpoints.MapControllerRoute(
                   name: "default",
                   pattern: $"{{culture}}/{{controller}}/{{action}}",
                   constraints: new
                   {
                       culture = new SiteCultureConstraint { HideLanguagePrefixForDefaultCulture = true },
                       controller = CONSTRAINT_FOR_NON_ROUTER_PAGE_CONTROLLERS
                   }
                );

                endpoints.MapControllerRoute(
                    name: "customone",
                    pattern: "{controller}/{action}",
                    constraints: new
                    {
                        controller = CONSTRAINT_FOR_NON_ROUTER_PAGE_CONTROLLERS
                    }
                );
            });
        }

Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run(); //test
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    }

Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <remove name="aspNetCore" />
            <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
        </handlers>
        <aspNetCore processPath=".\Ownership.exe" arguments=".\Ownership.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess">
            <environmentVariables>
                <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
            </environmentVariables>
        </aspNetCore>
    </system.webServer>
</configuration>

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "KenticoEventLog": {
      "LogLevel": {
        "Default": "Error",
        "Microsoft.AspNetCore.Server.Kestrel": "None"
      }
    }
  },
  "AllowedHosts": "*",
  "CMSHashStringSalt": "7426f0db-8abb-4480-8be0-19b8fc607ff2",
  "ConnectionStrings": {
    "CMSConnectionString": "Data Source=Server;Iny=Fitial Catalog=DB;User ID=User;Password=Password; Integrated Securitalse;Persist Security Info=False;Connect Timeout=60;Encrypt=False;Current Language=English;",
    "HorseRacingDataConnectionString": "Data Source=Server;Initial Catalog=DB;User ID=User;Password=Password; Integrated Security=False;Persist Security Info=False;Connect Timeout=60;Encrypt=False;Current Language=English;",
    "ReportingDataConnectionString": "Data Source=Server;Initial Catalog=DB;User ID=User;Password=Password; Integrated Security=False;Persist Security Info=False;Connect Timeout=60;Encrypt=False;Current Language=English;"
  },
  "CMSCIRepositoryPath": "C:\\KenitcoCore\\Ownership\\CMS\\App_Data\\CIRepository"

Does anyone know why the front end wouldn't be displaying even though it works locally? Any help would be appreciated.

Correct Answer

Francis Carroll answered on April 1, 2022 12:48

This issue was caused by the way the project was being published.

Initially it was being published as a Framework dependent project and was resolved by changing to the self-contained option.

0 votesVote for this answer Unmark Correct answer

Recent Answers


vasu yerramsetti answered on February 15, 2022 13:12

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.