Blazor WebAssembly 应用程序 - API 从浏览器调用 - 抱歉,此地址没有任何内容

Blazor WebAssembly App - API call from browser - Sorry, there's nothing at this address

更新:

在 Github ASP.NET 核心项目上创建了一个问题:

https://github.com/dotnet/aspnetcore/issues/32522

原文:

使用带有 Target Framework .NET 5.0 和 ASP.NET Core Hosted 的 Microsoft Visual Studio 2019 版本 16.9.4 创建了一个新的 Blazor WebAssembly 应用程序。

问题是,如果我在网站发布到 Azure Web 应用程序时从浏览器发出 API 调用,我会收到如下错误响应:

Sorry, there's nothing at this address.

如果我使用“清空缓存和硬重新加载”发出请求,一切都会按预期进行。

请求始终在 localhost 上工作。

不限于通过API加载的图像,JSON response的结果相同。

如何告诉 Blazor 不要 use/ignore 路由包含 /api/ 的 URL?

我读过 ASP.NET Core Blazor routing 但没有找到任何东西。

https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-5.0

错误消息来自 App.razor 文件:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
<MatPortalHost></MatPortalHost>

如果我在 App.razor 中使用默认值,结果相同:

<Found Context="routeData">
    <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
        <NotAuthorized>
            @if (!context.User.Identity.IsAuthenticated)
            {
                <RedirectToLogin />
            }
            else
            {
                <p>You are not authorized to access this resource.</p>
            }
        </NotAuthorized>
    </AuthorizeRouteView>
</Found>

图像控制器:

[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ImagesController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public ImagesController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet("{id}/file")]
    [AllowAnonymous]
    public async Task<ActionResult> GetImageDataFile(int id)
    {
        var image = await _context.Images.FindAsync(id);

        if (image == null)
        {
            return NotFound();
        }

        return File(image.Data, image.ContentType);
    }

Program.cs 对于 Blazor.Client:

namespace Blazor.Client
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");

            builder.Services.AddHttpClient("Blazor.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
                .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

            builder.Services.AddHttpClient<ImagesHttpClient>(client =>
                client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
                .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

            builder.Services.AddHttpClient<PostsAnonymousHttpClient>(client =>
                client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));

            // Supply HttpClient instances that include access tokens when making requests to the server project
            builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("Blazor.ServerAPI"));

            builder.Services.AddApiAuthorization();

            builder.Services.AddMatBlazor();

            await builder.Build().RunAsync();
        }
    }
}

Startup.cs for Blazor.Server, 完全没有修改:

namespace Blazor.Server
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddControllersWithViews();
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseIdentityServer();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });
        }
    }
}

发布配置如下所示:

调试起来真的很痛苦,但我最终找到了问题所在。

TLDR

Blazor\Client\wwwroot\index.html 中删除以下行:

<script>navigator.serviceWorker.register('service-worker.js');</script>

原文:

为了有某种开始,我必须在本地重现错误。我通过将我的应用程序发布到我的本地 IIS 而不是 IIS Express 来做到这一点。证书和 LocalDB 存在一些问题,但一段时间后我能够在本地重现错误。

然后我尝试创建一个新的应用程序以查看那里是否存在错误。在一个新的应用程序中,一切都按预期工作。然后我尝试退回到 Git 以查看错误是何时引入的。我最终在 Initial commit 结束,但错误仍然存​​在。

为了找到真正的错误,我首先尝试使用 WinMerge 来比较文件夹,但为了让它工作,我必须以相同的方式命名项目,因为每个 namespace 都会显示差异.

幸运的是,Meld 可以在比较文件和文件夹时忽略特定的单词。我在 Meld Preferences 下添加了两个 Text Filters 来匹配我想忽略的命名空间,然后比较结果。

现在除了 Client\wwwroot\ 文件夹之外几乎所有内容都相同。看着 index.html 我发现了一个很大的不同:

创建应用程序时,由于上面的 serviceWorker,我必须检查 Progressive Web Application

当我删除该行时,一切都按预期开始工作。

<script>navigator.serviceWorker.register('service-worker.js');</script>

然后我尝试创建一个设置了 Progressive Web Application 的新项目,并使用这些设置将其部署到我的本地 IIS:

加载网站后,我无法访问 https://localhost/_framework/blazor.boot.json 却没有看到 Sorry, there's nothing at this address.

如果您想继续使用 Progressive Web ApplicationService worker,您可以编辑 service-worker.published.js 并更新 shouldServeIndexHtml 以强制 url 像这样在服务器上呈现:

&& !event.request.url.includes('/api/')

你有没有检查过你的appSetting和你的restApi的url?可能你剩下的api的url仍然是localhost.you必须将它更改为你发布的服务器地址