locked
Issues Hosting ASP.Core 2.2 in IIS (inprocess) RRS feed

  • Question

  • User-1572561575 posted

    Hello,

    I am currently on defcon 2. I have a huge project which needed to be deployed yesterday but I can not get it run within IIS.

    It is written in C# with target framework Core 2.2.

    I have tried this so far and this one as well (on the application as well as a small scale test app.) and sadly non of those guides helped me out. It did not work and I got multiple different error which I will document later on.

    I really do not understand this because the iis express which gets configurated by visual studio during debug session never had an issue. It is still working there.

    Let me first show you my "Programm" class as well as my "Startup" class.

    public class Program
        {
            public static void Main(string[] args)
            {
                CreateWebHostBuilder(args).Build().Run();
            }
    
            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                    .UseStartup<Startup>();
        }

        public class Startup
        {
    
            public Startup(ILogger<Startup> logger, IConfiguration configuration)
            {
                _logger = logger;
                Configuration = configuration;
    
                if (UserManagementCache.GetInstance().Count <= 0)
                    UserManagementCache.GetInstance().InvalidateCache();
            }
    
            private readonly ILogger<Startup> _logger;
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
    
                
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
    
                services.Configure<RazorViewEngineOptions>(options => 
                {
                    options.FileProviders.Add(new CompositeFileProvider(
                        new EmbeddedFileProvider(
                            typeof(CurrentUserInfoControl).GetTypeInfo().Assembly,
                            "Web.Common"
                            )
                        ));
                });
    
                services.AddMemoryCache();
                services.AddDistributedMemoryCache();
                services.AddSession();
                services.AddKendo();
    
                services.AddAuthentication(IISDefaults.AuthenticationScheme);
    
                ServiceRegistrator.ConfigureServices(services);
                //services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");
                
                services.TryAddSingleton<IMenuHelper, MenuHelperImpl>(); 
                services.TryAddSingleton<IPageStateHelper, PageStateHelperImpl>();
                services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
                services.TryAddSingleton<IRoleEditStateHelper, RoleEditStateHelper>();
            
                services.AddMvc()
                    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                    .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Error");
                }
    
                app.UseStaticFiles();
                app.UseCookiePolicy();
                
                //enable session before MVC
                app.UseSession();
    
    
    
                app.Use(async (context, next) =>
                {
                    if (context.User.Identity != null)
                    {
                        var workContext = context.Session.GetSessionWorkContext();
                        var currentUserName = context.User.Identity.Name;
                        if (!string.IsNullOrEmpty(currentUserName))
                        {
                            if (workContext == null)
                            {
                                workContext = new WorkContext() { CurrentUser = new Core.Common.Business.UserToken(Guid.Empty, currentUserName) };
                                context.Session.SetSessionWorkContext(workContext);
                            }
                            else
                            {
                                if (workContext.CurrentUser != null)
                                {
                                    //User did change!
                                    workContext.CurrentUser = new Core.Common.Business.UserToken(Guid.Empty, currentUserName);
                                }
                            }
                        }
                        else
                        {
                            await context.Response.WriteAsync("Unable to identify the logged in user. Please try to login again via windows authentification.");
                        }
                    }
                    else
                    {
                        await context.Response.WriteAsync("Unable to identify the logged in user. Please try to login again via windows authentification.");
                    }
                    await next();
                });
    
                app.UseMvc();
    
    
    
            }
        }

    This is my current Web.Config:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <location path="." inheritInChildApplications="false">
        <!-- To customize the asp.net core module uncomment and edit the following section. 
      For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
        <system.webServer>
          <handlers>
            <remove name="aspNetCore" />
            <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
          </handlers>
          <aspNetCore  processPath="dotnet" arguments=".\Web.Administration.dll"  stdoutLogEnabled="true" stdoutLogFile="W:\Logs\Log" hostingModel="inprocess" />
          <security>
            <authentication>
              <anonymousAuthentication enabled="false" />
              <windowsAuthentication enabled="true" />
            </authentication>
          </security>
    	  </aspNetCore>
        </system.webServer>
      </location>
    </configuration>

    The IIS is configurated with:

    • Win Auth enabled
    • Anonym Login disabled
    • App pool created and that app pool has "No managed code" assigned.

    Now to the issue description.

    1)

    I published with Deployment Mode Self-Contained.

    In that combination I got a Internal Server Error 500.19 (screenshot) which is telling me that my configuration file is wrong.

    I did check out the msdn article about the support of Windows Auth for the core framework which can be found here.

    However I am unable to find the configuration issues.

    2)

    After I removed the authentication part in the web.config I got a bit further ahead. (Still the self-contained package from before except the modified web.config)

    Now I get a HTTP Error 500.31 - ANCM Failed to Find Native Dependencies (screenshot).

    The logfile is giving me strange informations. It says:

    ______________________________________________________________________

    Failed to load the dll from [C:\inetpub\WebAdmin\hostpolicy.dll], HRESULT: 0x800700C1

    An error occurred while loading required library hostpolicy.dll from [C:\inetpub\WebAdmin\]

    ______________________________________________________________________

    I double checked and the dll is existing withing the folder C:\inetpub\WebAdmin\

    3)

    Now it gets tricky. I tried another approach and changed the Deployment Mode from Self-Contained to "Framework-Dependend".

    The target Framework is still netcoreapp2.2.

    Here I get a HTTP Error 500.30 - ANCM In-Process Start Failure with not much info (screenshot)

    However the iis process is having a unhandled exception and thatfor the log which he should write has been created but no content is in there.

    This is actually a new behavior which I just got by walking through each step I tried so far.

    Before this behavior I got this error: Access to the path 'C:\WINDOWS\system32\config\systemprofile' is denied

    I tried to solve the access issue by giving the iis user the permission for this folder. The exception disapeared but I did not get the site. I got a random html content which bascially says "hello new asp.core user".

    ______________________________________________________________________

    All those things did not work and I am all out of ideas. Anyone has some ideas?

    One last thing that confuses me to no end. My Project is a ASP.NET Core mvc project.

    But in the project property site the  output it set to ConsoleApp (it actually generates the exe file as well as the equally named dll file). As I told you I have tried it on a smaller scale project. Which means I simply created an empy asp core app. In the project properties of this one it also had ConsoleApp set as output.

    However after I build it the ouput directory only had the dll and never an additional exe file. I am telling you this because as far as I know the inprocess hosting of asp core within iis required a dll as far as i know.

    I allways refered in the web.config to the dll but I am confused why the one project generates the console app and the other one does not (even thought both have console app as output).

    Additionally I of course have installed all the sdk (2.2-3.0) as well as the asp core hosting bundle (runtime & sdk 2.2-3.0)

    I hope you have some ideas because I really am stuck here.

    Best regards

    Simon

    Wednesday, October 2, 2019 6:20 AM

Answers

All replies

  • User-1764593085 posted

    Hi Q-Tec,

    Have your tried to use Remote Dubug to check whether it comes into your startup ConfigureServices and Configure method?

    https://docs.microsoft.com/en-us/visualstudio/debugger/remote-debugging-aspnet-on-a-remote-iis-computer?view=vs-2019

    Thursday, October 3, 2019 3:32 AM
  • User-1572561575 posted

    Hi Xing Zou,

    thank you for your reply. I will check that out later on. Since I need to get it to work rather fast I tried something before I saw your reply that actually got me further along my desired goal.

    I changed the website and its dependencies back to asp.Core 2.1 with the result that it actually loaded the site.

    However it does not work entirely as intended because he is unable to load some script libraries which are nessesary for the site to work properly.

    The browser is saying error 401 Unauthorized while trying to gain access to the lib folder. But everything else he can get access to. (Screenshot)

    I double checked it. Both the iss user as well as the app pool user has been given alle permission on that folder.

    I am not sure why this is happening right now.

    Best regards

    Simon

    Thursday, October 3, 2019 6:23 PM
  • User-1764593085 posted

    Hi Q-Tec,

    It seems that your static content does not work well,is it possible that you have referenced them in Development tag so In IIS (production) ,it does not wrok?

    https://stackoverflow.com/a/53306784/10158551

    The other static files are serverd from cache, have you tried to clean the cache and reload the site to check?

    To turn on static content,refer to https://stackoverflow.com/questions/10512053/css-images-js-not-loading-in-iis

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 7, 2019 1:36 AM
  • User-1572561575 posted

    Hi Xing Zou,

    thanks for the hints. I actually stumpled across that right after I posted it. Apparently the dev declared the script include within the development variable which of course was not within the web.config after it got deployed.  Now it is working as intended on Core 2.1 and I can get back to track down the issue on 2.2.

    Thank you for your help.

    Best regards

    Simon

    Friday, October 11, 2019 3:18 PM