ASP.NET Core 404 Error on IIS 10
Asked Answered
S

13

44

I have a problem with ASP.NET Core web application running on IIS 10. I am developing a Single Page Application with AngularJS.

The index.html loads perfectly but the backend requests are failing with 404 error code on the IIS 10. From Visual Studio with IIS Express it works perfectly.

Can anyone spot how can I fix the backend requests?

Here's my Program.cs

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

And here's my Configure method from Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseDefaultFiles();

    app.UseStaticFiles();

    app.UseIdentity();

    // Custom middleware for Angular UI-Router
    app.Use(async (context, next) =>
    {
        if (!Path.HasExtension(context.Request.Path.Value)
        && context.Request.HttpContext.Request.Headers["X-Requested-With"] != "XMLHttpRequest"
        && context.Request.Method.ToUpper() != "POST"
        && context.Request.Method.ToUpper() != "PUT"
        && context.Request.Method.ToUpper() != "DELETE")
        {
            await context.Response.WriteAsync(File.ReadAllText(env.WebRootPath + "/index.html"));
        }

        await next();
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "api/{controller=Home}/{action=Index}/{id?}");
    });
}
Supernal answered 22/7, 2016 at 14:35 Comment(4)
Enable ASP.NET Core logging (probably with a Debug log level) and see if there are any messages as to why this is failingSummerwood
Post your web.config too.Swords
Have you configured the MVC services?Swords
Have you added a Home controller with an Index action?Swords
S
24

You code is working on my machine with Kestrel. A good troubleshooting step is to find out whether the problem is with your ASP.NET Core application or with your IIS Hosting configuration.

Try this from the root of your project.

dotnet restore
dotnet run

You will see something like this:

Hosting environment: Production
Content root path: C:\MyApplicationPath
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

In your browser go to the following two URLs. If they don't work, then something is wrong with your application. If they do work, something is wrong with your IIS hosting.

localhost:5000        // you will see your index.html page
localhost:5000/api    // you will see your default routes output
Swords answered 23/7, 2016 at 0:23 Comment(5)
Thanks I could fix it. The problem was with my application but it is a little bit weird thing to throw a 404 error if something wrong with the application.Supernal
What was wrong with the application? What did your fix involve?Swords
The problem was a missing configuration file. I have 3 environment appsettings file for Development, Staging and Production with the necessary connection strings. The default publish option contains only the appsettings.json. So I need to change the value to appsettings*.json to copy all of the environment settings.Supernal
Very useful. My API is actually working through IIS and through running the EXE on the server. It seems it's my Swagger page that is giving me the 404.Dander
Mentioning Swagger gave me an idea, I was receiving 404 accessing example.com/mysitepoolname, it turns out I just need to access the correct URL at example.com/swagger/index.html and voila, works just fine. (hope to save someone from wasting time digging for a solution)Lomeli
W
33

In my case the problem was that my controller threw an exception, thus the framework tried to use the exception handler page which was no available, thus the 404 error, the controller itself was throwing 500 error

Wicklund answered 23/6, 2017 at 9:44 Comment(4)
How did you troubleshootSollars
Yeah, I would be interested to know too. In the development mode the exception should be showing on the page, but it isn't. Not sure if there is an exception that is causing my 404 or notSupplement
I think the routing is broken for some reason, I can get to the paga if I include the full path,... This will work -> localhost:5001/home/index.... This won't work -> localhost:5001/home neither this localhost:5001Supplement
for check this answer add try catch statement in you controllerDisenthrone
A
33

For the benefit of searchers.

I was getting a 404 when Using IIS. I had followed the correct procedure for publishing (here) and deployment as detailed here.

It took some time to figure out, but I eventually found the answer hidden in a Rick Strahl blog post.

Basically, when making the application pool, as well as setting it to 'No Managed Code', I also needed to go into the advanced settings and set the Application Pool Identity to 'Network Service'. It was fine under ApplicationPoolIdentity on my machine, but not on a machine I deployed to.

enter image description here

So, for clarity, my full procedure was:

To create package:

  1. Create dotnet core website (I used Visual Studio 2017)
  2. Publish. Could have used VS's publish function, but I used CLR via the package manager. The command was:

    dotnet publish -c Release -r win-x64 --self-contained

I had to use the win-x64 identifier as we have to be compatible with 64-bit Windows Server 2008.

To deploy:

  1. Make a folder in C:\inetpub\wwwroot (e.g. 'testsite')
  2. Take the contents of the publish folder ({root}\bin\Release\netcoreapp2.1\win-x64\publish) and copy it to the new 'testsite' folder (or your equivalent).
  3. Install the dotnet core runtime (not SDK!) on the host machine.
  4. Open IIS. Right click 'Application pools', then 'Add Application Pool'. Create one with the .NET CLR Version set to 'No Managed Code'.
  5. (my machine didn't need this step, but server did).Click on Application pools again. Right click your new App Pool and Choose 'Advanced Settings'. Change the identity to 'Network Service' (as shown in the picture above).
  6. Back at top level IIS, Expand 'Default Web Site', right click the folder of your website and choose 'Convert to application'. Choose your new App Pool with No Managed Code.
  7. Open command prompt as admin and iisreset . You should only need this the first time after you've installed the dotnet core runtime.
  8. Visit the site (e.g. http://localhost/testsite)
Abscise answered 13/9, 2018 at 13:39 Comment(2)
According to the MSDN docs you don't need to install the runtime when it's self contained: learn.microsoft.com/en-us/dotnet/core/deployingBouldon
@Bouldon - that's a good point - you wouldn't need it for self contained. You will of course still need the .NET Core IIS Hosting BundleAbscise
S
24

You code is working on my machine with Kestrel. A good troubleshooting step is to find out whether the problem is with your ASP.NET Core application or with your IIS Hosting configuration.

Try this from the root of your project.

dotnet restore
dotnet run

You will see something like this:

Hosting environment: Production
Content root path: C:\MyApplicationPath
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

In your browser go to the following two URLs. If they don't work, then something is wrong with your application. If they do work, something is wrong with your IIS hosting.

localhost:5000        // you will see your index.html page
localhost:5000/api    // you will see your default routes output
Swords answered 23/7, 2016 at 0:23 Comment(5)
Thanks I could fix it. The problem was with my application but it is a little bit weird thing to throw a 404 error if something wrong with the application.Supernal
What was wrong with the application? What did your fix involve?Swords
The problem was a missing configuration file. I have 3 environment appsettings file for Development, Staging and Production with the necessary connection strings. The default publish option contains only the appsettings.json. So I need to change the value to appsettings*.json to copy all of the environment settings.Supernal
Very useful. My API is actually working through IIS and through running the EXE on the server. It seems it's my Swagger page that is giving me the 404.Dander
Mentioning Swagger gave me an idea, I was receiving 404 accessing example.com/mysitepoolname, it turns out I just need to access the correct URL at example.com/swagger/index.html and voila, works just fine. (hope to save someone from wasting time digging for a solution)Lomeli
T
7

in my case, the problem was fixed by setting environment variable in the web.config

<aspNetCore processPath="dotnet"
      arguments=".\MyApp.dll"
      stdoutLogEnabled="false"
      stdoutLogFile=".\logs\stdout"
      hostingModel="inprocess">
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
     </environmentVariables>
</aspNetCore>
Tuppence answered 9/9, 2022 at 18:52 Comment(0)
H
5

I was missing a key file - web.config which IIS needs in order to run your web application. I used the web.config configurations specified here:

https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/web-config?view=aspnetcore-5.0

Specifically, the configurations for ASP.NET Core Module.

Heiser answered 16/7, 2021 at 14:0 Comment(0)
T
3

For anyone here with the same issue, it may not be an issue with your deployment. If you are deploying the default sample web api project (WeatherForecastAPI) and then received 404, it is because swagger is not enabled in production or release mode. So there are no controller method to handle the to receive the requests sent to root url.

However if you call the endpoint directly (in this case {your_app_url}/WeatherForecast) then it will work.

Thumbscrew answered 1/5, 2023 at 19:1 Comment(0)
E
1

Another very silly but probable variant is that the app was deployed in folder different from what you were expecting (ex: your server root instead of sub-folder) due to erroneous deploy settings.

Euphrosyne answered 8/7, 2019 at 7:18 Comment(0)
F
1

Had the same issue now which brought me to this page. In case anyone is having this issue now this was what fixed it for me:

  1. Downloaded and installed dotnet-hosting-3.1.4-win from https://dotnet.microsoft.com/download/dotnet-core/thank-you/runtime-aspnetcore-3.1.4-windows-hosting-bundle-installer

  2. Downloaded and installed dotnet-sdk-2.2.207-win-x64 from https://dotnet.microsoft.com/download/dotnet-core/2.2

Frederick answered 30/5, 2020 at 13:35 Comment(0)
T
1

If you are using an api call make sure your class has:

[Route("api/[controller]")]
    [ApiController]

above where the class is instantiated.

Also make sure you have:

[HttpGet()]

for example above the api method you are trying to debug.

Taxiplane answered 20/7, 2020 at 2:52 Comment(0)
E
1

I had configured a root directory using .AddRazorPageOptions(rpo => rpo.RootDirectory = "/Folder"), but I forgot and my .cshtml files were still in the root of the project instead. I just had to make the /Folder folder and put my files in there and it worked.

Expanse answered 10/1, 2023 at 18:31 Comment(0)
I
0

For me the issue was an ISAPI Filter called UrlScan. I had to delete it from the application, only then did it work.

Issacissachar answered 18/10, 2020 at 16:25 Comment(0)
C
0

I was missing a handler mapping for AspNetCoreModuleV2.

Request Path: *
Module: AspNetCoreModuleV2
Executable: blank
Name: aspNetCore (this I believe can be anything you want)

Under Request Restrictions, I unchecked the "Invoke handler only if request is mapped to:" checkbox. Selected All verbs, and Script access.

Chromatogram answered 30/1, 2023 at 19:52 Comment(0)
I
0

404 problem will be ok when you add this code to your program.cs file:

app.MapControllerRoute(name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
Initial answered 15/9, 2023 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.