gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:09:34 42 4
gpt4 key购买 nike

更新:
在 Github ASP.NET Core 项目上创建了一个问题:
https://github.com/dotnet/aspnetcore/issues/32522
原文:
使用 Microsoft Visual Studio 2019 版本 16.9.4 和 Target Framework .NET 5.0 和 ASP.NET Core Hosted 创建了一个新的 Blazor WebAssembly 应用程序。
问题是,如果我在将站点发布到 Azure Web 应用程序时从浏览器进行 API 调用,我会收到如下错误响应:

Sorry, there's nothing at this address.


enter image description here
如果我使用“空缓存和硬重新加载”发出请求,一切都会按预期进行。
enter image description here
该请求始终适用于 localhost .
不限于通过 API 加载的图像, JSON response 的结果相同.
enter image description here
enter image description here
我怎么知道 Blazor不使用/忽略包含 /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>
图像 Controller :
[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.csBlazor.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.csBlazor.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");
});
}
}
}
发布配置如下所示:
enter image description here

最佳答案

这对调试来说真的很痛苦,但我最终发现了问题。
TLDR
Blazor\Client\wwwroot\index.html 中删除下面的行:

<script>navigator.serviceWorker.register('service-worker.js');</script>
原文:
为了有某种开始,我必须在本地重现错误。我通过将我的应用程序发布到我的本地 IIS 而不是 IIS Express 来做到这一点。证书和 LocalDB 存在一些问题但我能够在一段时间后在本地重现该错误。
Blazor WebAssembly App with Individual Accounts and ASP.NET Core Hosted - IIS - SQLLocalDB 15.0 The specified resource language ID cannot be found
然后我尝试创建一个新应用程序以查看那里是否存在错误。在一个新的应用程序中,一切都按预期工作。然后我试图退回 Git查看何时引入错误。我最终到达了 Initial commit并且错误仍然存​​在。
为了找到我第一次尝试使用 WinMerge 的实际错误比较文件夹,但为了使其工作,我必须为项目命名相同的名称,因为每个 namespace否则会显示差异。
enter image description here
幸运的是,在比较文件和文件夹时,Meld 可以忽略特定的单词。我在 Meld Preferences 下添加了两个与我想忽略的命名空间相匹配的文本过滤器,然后比较了结果。
https://stackoverflow.com/a/46162831/3850405
现在几乎所有东西都是相同的,除了 Client\wwwroot\文件夹。看着 index.html我注意到一个很大的不同:
enter image description here
创建应用程序时,我必须检查 Progressive Web Application由于 serviceWorker以上。
enter image description here
当我移除这条线时,一切都开始按预期工作。
<script>navigator.serviceWorker.register('service-worker.js');</script>
然后我尝试使用 Progressive Web Application 创建一个新项目使用以下设置将其设置并部署到我的本地 IIS:
enter image description here
加载网站后我无法访问 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/')

关于c# - Blazor WebAssembly 应用程序 - 来自浏览器的 API 调用 - 抱歉,此地址没有任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67452439/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com