Ogg*_*las 2 c# asp.net-web-api asp.net-core blazor blazor-webassembly
更新:
在 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 调用,我会收到如下错误响应:
抱歉,此地址没有任何内容。
如果我使用“空缓存和硬重新加载”发出请求,一切都会按预期进行。
该请求始终适用于localhost
。
它不仅限于通过 API 加载的图像,对于JSON response
.
如何判断Blazor
不使用/忽略包含 的 URL 的路由/api/
?
我已经读过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>
Run Code Online (Sandbox Code Playgroud)
如果我在 中使用默认值,结果相同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>
Run Code Online (Sandbox Code Playgroud)
图像控制器:
[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);
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
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");
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
发布配置如下所示:
这对调试来说真的很痛苦,但我最终发现了问题。
TLDR
从以下内容中删除以下行Blazor\Client\wwwroot\index.html
:
<script>navigator.serviceWorker.register('service-worker.js');</script>
Run Code Online (Sandbox Code Playgroud)
原来的:
为了有某种开始,我必须在本地重现错误。我通过将我的应用程序发布到我的本地 IIS 而不是 IIS Express 来做到这一点。证书存在一些问题,并且LocalDB
但一段时间后我能够在本地重现该错误。
带有个人帐户和 ASP.NET Core 托管的 Blazor WebAssembly 应用程序 - IIS - SQLLocalDB 15.0 找不到指定的资源语言 ID
然后我尝试创建一个新应用程序以查看那里是否存在错误。在一个新的应用程序中,一切都按预期工作。然后我尝试回过头Git
来看看什么时候引入了错误。我最终在Initial commit
错误仍然存在。
为了找到我首先尝试WinMerge
比较文件夹的实际错误,但为了使其工作,我必须为项目命名相同的名称,namespace
否则每个项目都会显示差异。
幸运的是,在比较文件和文件夹时,Meld 可以忽略特定的单词。我在 Meld Preferences 下添加了两个与我想忽略的命名空间相匹配的文本过滤器,然后比较了结果。
现在,除了Client\wwwroot\
文件夹之外,几乎所有内容都相同。看着index.html
我发现了一个很大的不同:
Progressive Web Application
由于serviceWorker
上述原因,在创建应用程序时,我必须进行检查。
当我移除这条线时,一切都开始按预期工作。
<script>navigator.serviceWorker.register('service-worker.js');</script>
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用Progressive Web Application
set创建一个新项目,并使用以下设置将其部署到我的本地 IIS:
加载网站后,我无法访问https://localhost/_framework/blazor.boot.json
而没有看到Sorry, there's nothing at this address.
。
如果您想继续使用Progressive Web Application
,Service worker
您可以编辑service-worker.published.js
和更新shouldServeIndexHtml
以强制 url 像这样在服务器上呈现:
&& !event.request.url.includes('/api/')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
948 次 |
最近记录: |