3

I created an ASP.Net Core 2.2 Web Api Project and it is running locally without any issue. After I publish it to the file system, it is always giving me 404 issue. I have enabled windows fetures related to IIS and asp.net framework web api2 applications are running well in the same server.

I have enabled swagger doc and has used Microsoft.AspNetCore.Authentication libs too.

Program.cs

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace US.BOX.AuthAPI
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

Startup.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using US.BOX.AuthAPI.Extensions;

namespace US.BOX.AuthAPI
{
    public class Startup
    {
        private readonly IConfiguration _configuration;
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        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<IISOptions>(options =>
            {
                options.ForwardClientCertificate = false;
            });

            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton<IAuthenticationSchemeProvider, CustomAuthenticationSchemeProvider>();

            services.AddSwaggerDocumentation();
            services.AddJwtBearerAuthentication(_configuration);

            services.AddCors();
            services.AddLogging();

            services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ILogger<Startup> logger)
        {
            app.UseAuthentication();

            if (env.IsDevelopment())
            {
                app.UseSwaggerDocumentation();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

appsettings.json

{
  "JWT": {
    // TODO: This should be updated for production deployment
    "SecurityKey": "sDIkdjhkalUthsaCVjsdfiskokrge",
    "Issuer": "https://{host_name}:{port}",
    "Audience": "https://{host_name}:{port}",
    "ExpirationTimeInMinutes": 60
  },
  "Logging": {
    "LogFilePath": "Logs/auth-{Date}.txt",
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

UsersController.cs

using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace US.BOX.AuthAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetAll()
        {
            try
            {
                return Ok("Users");
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}

After I published it generates following web.config file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\US.BOX.AuthAPI.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" />
    </system.webServer>
  </location>
</configuration>
Janith Widarshana
  • 3,213
  • 9
  • 51
  • 73
  • This link might be helpful for You https://stackoverflow.com/questions/38529123/asp-net-core-404-error-on-iis-10 – SUNIL DHAPPADHULE May 28 '19 at 10:02
  • Select your application in IIS and click the browse link in the right-side pane. Is that the URL you are trying to hit it with? – Crowcoder May 28 '19 at 11:01
  • Yes, I have hosted it under port 8081. So trying to access it via http://localhost:8081/ – Janith Widarshana May 28 '19 at 11:14
  • Is it set as the default website or an application under a website? What I was trying to get at is that it might be something like `http://localhost//api/Users` – Crowcoder May 28 '19 at 12:31
  • Hey @JanithWidarshana, I can see you have swagger. Can you see the swagger documentation when you run the API? Oh... I saw it later. It won't show you swagger documentation in production, since it is only used in development only. Just take it out of there and check whether it shows you the swagger documentation in prod as well. – Oshadha May 28 '19 at 12:41
  • @Oshadha yes I have swagger doc and it can only see on dev mode. In dev mode I can see it. But after I hosted it in iis I tried to access http://localhost:8081/api/users that always gives me 404. And I tried a basic app with default controller that VS 2017 create. It also gives me 404 after hosting on IIS. – Janith Widarshana May 28 '19 at 16:44
  • 1
    @JanithWidarshana IIS has the concept of sites and applications. If you are not replacing the Default Web Site with this deployment then it will not be at `localhost:port/api/users`, it will be at `localhost:port//api/users` – Crowcoder May 28 '19 at 19:09
  • 1
    @JanithWidarshana, If you take out the app.UseSwaggerDocumentation(); out of the IF condition you will be having the swagger docs in prod. Please do it see whether it works in IIS. Second thoughts, can you just try this http://localhost:8081/api/users in https://www.getpostman.com/. – Oshadha May 29 '19 at 05:00
  • Still facing the same issue. As I feel it can be an IIS issue, means I have missed something to install or configure. – Janith Widarshana May 29 '19 at 05:20
  • It is an issue with using swagger. Finally, I change the way of using swagger and it works. Thanks all for supporting. – Janith Widarshana May 29 '19 at 06:34

2 Answers2

2

below are some of the checklist you can check if you have done it.

  1. Install windows-hosting-bundle-installer for you dotnet core version for your OS. you can download it from the below link
  2. Create a new application pool in you IIS for dotnet core you can check the below images for the settings enter image description here
  3. Target any application related to dotnet core to the newly created app pool, for all the hosting.

see if the above solves the issue. revert for any queries vote and like if your issue is resolved so that it might help someone.

Pabitro
  • 36
  • 5
  • Can you share your Controller code to better understand – Pabitro May 28 '19 at 10:14
  • Updated question with controller class.. I just created .net core 2.2 web api project from the sketch and did not change anything and tried to publish it. It also giving same issue. Could anyone try that please. – Janith Widarshana May 28 '19 at 10:20
2

Hope this will help someone. Followings are the steps I did for solving this issue.

  1. Enable IIS Hostable Web Core

    enter image description here

  2. Install ‘Visual C++ Redistributable for Visual Studio 2015’

    https://www.microsoft.com/en-us/download/details.aspx?id=48145

  3. Install ‘dotnet-hosting-2.2.6-win.exe’

    https://dotnet.microsoft.com/download

  4. Create separate IIS Application pool with ‘No Manage Code’ in .NET CLR Version

    enter image description here

** Note order of doing above steps is very important

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Janith Widarshana
  • 3,213
  • 9
  • 51
  • 73