以下解决方案假定您在开发环境中使用 Auth0 的示例应用程序进行 Auth0 身份验证。这是修复 404 错误并允许 React 客户端调用 .Net Core 服务器上的端点的配置。
我的服务器目录设置为默认静态文件目录名称“wwwroot”,但您可以将其命名为其他名称。
将 React 构建文件复制到此目录。
+--api
|
+--bin
|
+--wwwroot // Copy build files to this directory
|
--project file1
:
--project file N
在.Net Core Startup.cs服务器代码中,修改ConfigureServices()如下
ConfigureServices(IServiceCollection services)
{
// Other code
// Add this
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "wwwroot";
});
}
在.Net Core Startup.cs服务器代码中,修改Configure()如下
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseSpaStaticFiles(); // Add this call to UseSpaStaticFiles()
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
// Add this call to UseSpa(). NOTE: This call must be after app.UseEndpoints()
// above so that your client can call your api endpoints before the React router
// can modify the routes
app.UseSpa(spa =>
{
spa.Options.SourcePath = "wwwroot";
});
}
在您的 React 应用程序中,您可能有与此类似的代码调用需要身份验证的端点:
fetch("https://localhost:5001/api/weather/getforecast", {
headers: {
Authorization: `Bearer ${this.props.auth.getAccessToken()}`,
},
})
我正在使用 launchSettings.json 文件中设置的默认端口运行服务器应用程序。
一旦我如上所示配置了所有内容,Auth0 就能够在没有 404 的情况下调用 /callback 路由(因为它实际上并不存在于服务器上),并且 React 客户端能够在登录后访问需要身份验证的端点客户端应用程序。
我仍在学习很多关于 .Net Core 的知识,所以如果您知道更好的方法,请发表评论!