Forum Discussion

AlexTekeuf's avatar
AlexTekeuf
Copper Contributor
Nov 22, 2024
Solved

React website with ASP.NET and IIS : API not working

Hi,

I have found a lot of similar issues on the web but none was working for me, and I am so desperate after days so I am posting here and hope someone can help.

I have an ASP.NET server that serves a React website, and also works as an API for the website itself. The server runs on a Windows 11 PC with IIS, in C:/MyWebSite. This folder contains the ASP.NET server (.exe, .dll, etc), the IIS configuration (web.config) and the build React website (index.html, favicon.ico and assets folder).

The server succeed to show my main page, but it fails doing an API request. The API request fails as well when I call it from Postman, and gives me the error "HTTP 404.0 - Not Found" with these details :

  • Module IIS Web Core
  • Notification : MapRequestHandler
  • Handler : StaticFile
  • Error code : 0x80070002

FYI, the request is GET http://localhost:5058/api/configuration/settings

 

Concerning ASP.NET, here is my Program.cs :

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

// Create the web application builder
var builder = WebApplication.CreateBuilder(args);

// JWT authentication
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    string? tKey = builder.Configuration["Jwt:Key"];

    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = tKey != null ? new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tKey)) : null
    };
});

// Add the controllers to the application (for input http requests)
builder.Services.AddControllers();

// Configure CORS policy
builder.Services.AddCors(options => {
    options.AddPolicy("AllowAllOrigins",
        builder => {
            builder.AllowAnyOrigin()
                   .AllowAnyHeader()
                   .AllowAnyMethod();
        });
});

// Create the App
var app = builder.Build();

// Applies the CORS policy
app.UseCors("AllowAllOrigins");

// Serving the static files
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();

// Map the routes to the controllers
app.MapControllers();

// Undefined route will lead to index.html
app.MapFallbackToFile("index.html");

// Run the App
app.Run();

Of course, I have created some controllers, here is ConfigurationController.cs for example :

using Microsoft.AspNetCore.Mvc;

namespace AspReact.Server.Controllers
{
    [ApiController]
    [Route("api/configuration")]
    public class GeneralController : ControllerBase
    {
        [HttpGet("settings")]
        public ActionResult GetSettings()
        {
            return Ok(new
            {
                language = 'fr',
                theme = 0
            });
        }

        [HttpPost("settings")]
        public ActionResult SetSettings([FromQuery] string language, [FromQuery] string theme)
        {
            m_tLanguage = language;
            m_tTheme = theme;

            return Ok();
        }
    }
}

Here is my IIS configuration :

<?xml version="1.0"?>
<configuration>
	<system.webServer>
		<rewrite>
			<rules>
				<rule name="React Routes" stopProcessing="true">
					<match url=".*" />
					<conditions logicalGrouping="MatchAll">
						<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
						<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
						<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
					</conditions>
					<action type="Rewrite" url="/" />
				</rule>
			</rules>
		</rewrite>
	</system.webServer>
</configuration>

NB : At first I was not doing :

<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />

And the API request was returning the content of index.html... If it can help.

Please note that all this is working during development with the server running in a debug console.

 

I would be grateful for any help! Thanks.

  • Hello, it seems that your IIS server is missing some package. Have you checked this tutorial? It says that you need to install .NET Core Hosting Bundle and Web Management Service. 

    https://learn.microsoft.com/en-us/visualstudio/deployment/quickstart-deploy-aspnet-web-app?view=vs-2022&tabs=web-server

  • AlexTekeuf's avatar
    AlexTekeuf
    Copper Contributor

    Yes indeed, after reinstalling the .NET Core Hosting Bundle, it works now ! I suspect I installed the wrong version at first.... Thanks !

  • diogokobbi's avatar
    diogokobbi
    Brass Contributor

    Hello, it seems that your IIS server is missing some package. Have you checked this tutorial? It says that you need to install .NET Core Hosting Bundle and Web Management Service. 

    https://learn.microsoft.com/en-us/visualstudio/deployment/quickstart-deploy-aspnet-web-app?view=vs-2022&tabs=web-server

Resources