admin管理员组

文章数量:1122832

I have found a lot of similar issues on the web but none was working for me.

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" />

But the API request was returning the content of index.html.

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

What can I try next?

本文标签: cReact website with ASPNET and IISAPI not workingStack Overflow