You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor WASM部署Azure后手动输入子路由URL出现404问题求助

Blazor WASM部署到Azure后手动输入URL返回404的解决方案

这个问题的核心是Blazor WASM作为单页应用(SPA),所有路由逻辑都在客户端处理,但Azure服务器收到直接输入的URL请求时,会尝试在服务器上查找对应文件或目录,找不到就返回404。以下分部署场景给出解决方案:

场景1:部署到Azure静态Web Apps

  1. 在项目根目录创建staticwebapp.config.json文件,添加以下配置:
{
  "routes": [
    {
      "route": "/*",
      "serve": "/index.html",
      "statusCode": 200
    }
  ]
}
  1. 确保该文件会被包含在发布输出中:打开项目的.csproj文件,添加或确认以下内容:
<ItemGroup>
  <Content Include="staticwebapp.config.json" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
  1. 重新发布应用,所有路由请求会被转发到index.html,由Blazor客户端路由处理。

场景2:部署到Azure App Service(Windows主机)

  1. 确保项目根目录的web.config配置正确,替换为以下内容:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Blazor WASM Rewrite" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>
  1. 确认.csproj中包含web.config的发布配置:
<ItemGroup>
  <Content Include="web.config" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
  1. 登录Azure门户,进入你的App Service:
    • 转到配置 > 常规设置,确保「启用静态内容」处于开启状态
    • 检查扩展,确认URL重写模块已安装(Windows App Service默认启用)
  2. 重新发布应用,测试手动输入URL的情况。

场景3:部署到Azure App Service(Linux主机)

Linux主机通常使用Apache或Nginx,以下是Apache的处理方式:

  1. 在项目根目录创建.htaccess文件,添加以下规则:
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
  1. 确认.csproj中包含该文件的发布配置:
<ItemGroup>
  <Content Include=".htaccess" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
  1. 重新发布应用。

额外检查点

  • 发布后本地查看bin/Release/netX.X/publish目录,确认对应的配置文件(staticwebapp.config.json/web.config/.htaccess)已存在
  • 测试前清除浏览器缓存,避免旧缓存影响结果

内容的提问来源于stack exchange,提问作者Steve Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 08:07:22