[英]Blazor WASM Route Post Request to index.html
我有一個使用 Visual Studio 模板設置的 Blazor WASM 應用程序。 我在 Server 項目的 Startup.cs 文件中的路由如下所示:
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html",);
});
每當我發出 GET 請求我沒有 controller 的路由時,這一直工作得很好,並為我的客戶項目中的 wwwroot/index.html 文件提供服務。 客戶端項目中的 Blazor 框架將其用於那里。 但是,我現在需要支持將 index.html 文件從 GET 或 POST 請求返回到我的應用程序中沒有 controller 的端點。 我很難弄清楚如何設置它。 我已經嘗試過EndpointRouteBuilderExtensions.MapPost方法並且能夠返回字符串,但沒有看到任何使用它返回文件的好例子。 這不起作用:
endpoints.MapPost("*", (HttpContext context) => {
context.Request.Path = "/index.html";
context.SetEndpoint(null);
});
雖然它類似於框架方法 StaticFilesEndpointRouteBuilderExtensions.MapFallbackToFile 所做的事情: https://github.com/dotnet/aspnetcore/blob/fc4e391aa58a9fa67fdc3a96da6cfcadd0648b17/src/Middleware/StaticFiles/src.csRouteic#Liddleware/StaticFilesEndpointBuilderExtensions/src.csRouteic
我的問題與此類似: 如何在 ASP 中 map 到 static 文件的端點。 網絡核心? 但是那里的答案不適用於我的情況。
我有一種方法可以幫助你。 您可以告訴網絡服務器將它找不到的任何路由路由到您的 index.html。 Nginx 中的語法是
try_files $uri $uri/ /index.html =404;
不確定這是否能解決您的問題,因為我尚未使用 Wasm 中的 Api 控制器對此進行測試。
在閱讀了更多的 aspnetcore 源代碼和 MapFallbackToFile 之后,我想出了這個對我有用的解決方案。 我的服務器解決方案的 Startup.Configure 方法有:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapPost("{*path:nonfile}", CreatePostIndexRequestDelegate(endpoints));
endpoints.MapFallbackToFile("index.html");
});
我在 Startup class 中添加了這個新方法:
//This method allows Post requests to non-file, non-api endpoints to return the index.html file
private static RequestDelegate CreatePostIndexRequestDelegate(IEndpointRouteBuilder endpoints)
{
var app = endpoints.CreateApplicationBuilder();
app.Use(next => context =>
{
context.Request.Path = "/index.html";
context.Request.Method = "GET";
// Set endpoint to null so the static files middleware will handle the request.
context.SetEndpoint(null);
return next(context);
});
app.UseStaticFiles();
return app.Build();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.