集成Identity的ASP.NET Core+React项目Azure发布报错咨询
问题核心原因
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 报错的本质是:前端预期返回JSON的接口请求,被重写规则拦截后返回了index.html的HTML内容,首字符为<导致解析失败。结合Identity集成场景,问题来自重写规则错误、中间件顺序错误、配置文件冲突三类。
修复步骤
1. 修正重写规则
你当前web.config中的重写规则存在两处错误:一是^/ (api)的/后多余空格导致API路由未被排除,二是未排除Identity、IdentityServer相关的后端路由。将根目录web.config的重写规则替换为如下内容,同时删除wwwroot目录下多余的第二份web.config,避免规则冲突:
<?xml version="1.0"?> <configuration> <system.webServer> <!-- 静态资源MIME配置 --> <staticContent> <mimeMap fileExtension=".woff2" mimeType="application/x-font-woff" /> <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" /> <mimeMap fileExtension=".json" mimeType="application/json" /> </staticContent> <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|identity|.well-known)" negate="true" /> </conditions> <action type="Rewrite" url="/" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
2. 修正Startup.cs中间件顺序
中间件顺序错误会直接导致认证逻辑失效、路由匹配错误,按照如下顺序调整:
app.UseHttpsRedirection(); // 静态文件中间件放在最前 app.UseStaticFiles(); app.UseRouting(); // 认证、IdentityServer、授权必须放在路由之后,端点映射之前,顺序不能乱 app.UseAuthentication(); app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); // 配置React回退路由,未匹配到后端路由时自动返回index.html endpoints.MapFallbackToFile("index.html"); });
3. 调整发布配置
不要手动修改发布后的目录结构,在项目.csproj文件中添加如下配置,发布时会自动将React打包产物放到wwwroot目录下:
<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish"> <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" /> <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" /> <ItemGroup> <DistFiles Include="$(SpaRoot)build\**" /> <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)"> <RelativePath>wwwroot\%(RecursiveDir)%(FileName)%(Extension)</RelativePath> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> <ExcludeFromSingleFile>true</ExcludeFromSingleFile> </ResolvedFileToPublish> </ItemGroup> </Target>
4. 验证Azure配置
- 关闭Azure应用服务自带的「身份验证(Easy Auth)」功能,避免与自定义集成的Identity冲突
- 将应用配置中的
ASPNETCORE_ENVIRONMENT参数设置为Production - 确保你在本地用户机密中存储的
ClientId、ClientSecret,已经添加到Azure应用服务的「配置」-「应用程序设置」中,生产环境不会读取本地用户机密。
内容的提问来源于stack exchange,提问作者domshyra
相关产品推荐
相关产品推荐

