4

从零开始Blazor Server(8)--增加菜单以及调整位置 - jvx

 2 years ago
source link: https://www.cnblogs.com/j4587698/p/16554744.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

这篇文章主要是把前面的一些东西稍微调整一下,使其更适合后面的内容。

主要是两个事,一个是把原来的PermissionEntity直接变成MenuEntity,直接让最后一级是菜单,这样后面就简单很多。

另外增加一些默认的菜单为后面的文章做准备。

另外就是调整一下Pages里面的目录结构,让我们不用每个页面都去加@attribute [Authorize]

处理目录结构

之前的内容里,我们最后还是用了Furion自带的方法来处理成策略授权了,所以我们正常的话需要每个页面都加上@attribute [Authorize]

但是这样太麻烦了,幸好微软给我们提供了一个_Imports.razor的东西,这个文件是目录级的,我们可以在某层目录下添加,然后此目录和它的子目录都会受影响。

所以我们就需要把Login和其他的页面分开,因为我们的Login页面是不需要登录的,而且分开以后更清晰。

这里在Pages下面新建两个目录,一个叫Account,一个叫Admin。这里把Login.razor放到Account目录下,把其他的razor文件都放到Admin下面。

这里注意不要移动那两个cshtml文件,因为那两个文件的位置如果改变还需要改变很多其他的东西。

然后在Admin目录下新建一个_Imports.razor,内容为:

@attribute [Authorize]

这样,所有的Admin目录下的页面都会受到影响,需要权限验证。

修改MenuEntity

在之前,我们是做了个PermissionEntity,里面只记录了权限信息,但是这样就还需要一套菜单系统,然后还要根据Url来进行匹配,就太麻烦了一点,所以这里我们直接把菜单系统和权限系统合起来,把PermissionEntity改为MenuEntity,并且增加IconParentId用于菜单使用。

修改后的MenuEntity如下:

[Description("菜单表")]
public class MenuEntity: BaseEntity<MenuEntity, int>
{
    [Description("菜单名")]
    public string? Name { get; set; }

    [Description("菜单图标")]
    public string? Icon { get; set; }

    [Description("对应页面Url")]
    public string? Url { get; set; }

    [Description("父菜单ID")]
    public int ParentId { get; set; }

    [Navigate(nameof(ParentId))]
    public MenuEntity? Parent { get; set; }

    [Navigate(nameof(ParentId))]
    public List<MenuEntity>? Children { get; set; }
    
    [Description("角色")]
    [Navigate(ManyToMany = typeof(RoleMenuEntity))]
    public virtual ICollection<RoleEntity>? Roles { get; set; }
}

同时我们增加一部分菜单项到DbExtension,这块代码就不贴了,直接去github看把。

源码在github:https://github.com/j4587698/BlazorLearn,分支lesson8。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK