如何为服务器端 Blazor 应用程序生成 xml 站点地图



>有谁知道为 Blazor 应用程序生成 xml 站点地图的方法? 尝试通过许多在线可用的生成器工具生成一个,但似乎没有一个生成准确的 XML 站点地图

在代码@Vi100的帮助下,我创建了一个名为Site Map的类,并在startup.cs文件中调用它。

网站地图.cs

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
public class Sitemap {
public static async Task Generate(HttpContext context) {
var pages = Assembly.GetExecutingAssembly().ExportedTypes.Where(p =>
p.IsSubclassOf(typeof(ComponentBase)) && p.Namespace == "your namespace.Pages");
foreach(var page in pages) {
// Do whatever you want with the page components, e.g. show it's name:
await context.Response.WriteAsync(page.FullName + "n");
// From here you can access most part of the static info about the         
//component,
// but if you want to get the page titles or similar info, you'll have to 
//create
// some custom attributes and decorate the pages with them.
}
}
}

并更改启动.cs

app.UseEndpoints(endpoints => {
endpoints.MapGet("/sitemap.xml", async context => {
await Sitemap.Generate(context);
});
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ConnectionHub>("/ConnectionHub");
endpoints.MapGet("/sitemap.xml", async context =>
{
await context.Response.WriteAsync(SitemapService.GetSitemap());
});
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

这条线指向。地图获取

路由可以直接在顶层注册,不需要嵌套在 UseEndpoint 调用中。

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/sitemap.xml", () => SitemapService.GetSitemapAsync());
app.Run();

为了使其正常工作,您需要构建一个服务,该服务使用xml站点地图返回字符串:

public class SitemapService
{
public static async Task<string> GetSitemapAsync()
{
//build here your sitemap 
return "this is my sitemap";
}
}

不能从 Blazor 服务器应用程序中获取站点地图。如果您假装以传统方式使用站点地图来声明如何在应用程序的页面中导航,那么您的运气不好,因为 blazor 应用作为单页应用程序提供,仅公开一个 url 作为入口点,对应于您为"_Host.cshtml"文件定义的路由点...

如果我之前的假设是错误的,并且出于任何原因想要某种内部站点地图,那么您可以使用反射来迭代应用程序中的所有页面并构建您需要的任何文档格式:

@page "/"
@using System.Linq;
@using System.Reflection;

<button @onclick="@SearchForPages">Search for pages</button>
@code{
private void SearchForPages()
{
// Get all the components derived from ComponentBase that are in the "YourAppName.Pages" namespace
// (adjust filter conditions if necessary...)
var pages = Assembly.GetExecutingAssembly()
.ExportedTypes
.Where(p => p.IsSubclassOf(typeof(ComponentBase)) && p.Namespace == "YourAppName.Pages");
foreach (var page in pages)
{
// Do whatever you want with the page components, e.g. show it's name:
Console.WriteLine(component.ToString());

// From here you can access most part of the static info about the component,
// but if you want to get the page titles or similar info, you'll have to create
// some custom attributes and decorate the pages with them.
}
}
} 

希望对你有帮助

相关内容

  • 没有找到相关文章

最新更新