当前位置: 移动技术网 > IT编程>开发语言>c# > asp.net core mvc权限控制:在视图中控制操作权限

asp.net core mvc权限控制:在视图中控制操作权限

2019年07月18日  | 移动技术网IT编程  | 我要评论

在asp.net core mvc中提供了权限验证框架,前面的文章中已经介绍了如何进行权限控制配置,权限配置好后,权限验证逻辑自动就会执行,但是在某些情况下,我们可能需要在代码里或者视图中通过手工方式判断权限,我们现在就来介绍下具体的操作方法。

如果在控制器方法里想要判断当前用户是否具有某个权限,可以直接使用httpcontext.user.hasclaim(string cliamtype,string cliamvalue)方法进行判断,该方法返回bool类型,返回true表示具有权限,否则不具有。

在视图上我们往往需要控制某个按钮或者超链接的权限,具有权限按钮就显示,否则不现实。那怎么样才能达到这样的效果?方法介绍如下:

1,在视图中直接使用httpcontext.user.hasclaim(string cliamtype,string cliamvalue)判断权限,然后控制按钮是否显示

@if(httpcontext.user.hasclaim("user","delete"))
{
<input type='button' value="删除"/>
}

上面的代码写在视图中,表示如果具有用户的删除权限,就显示删除按钮。这种方式比如在所有需要验证的地方,都按照这样的格式去书写。

2,借助于asp.net core mvc的新特性taghelper可以简化第一种方式,至于什么是taghelper,以及它的作用这里就不再介绍,大家可以百度或谷歌搜索,这里直接介绍如何自定义权限验证的taghelper。

<a asp-claim="goods,edit" asp-action="addgoods" asp-route-id="@goods.id" class="btn-icon " title="编辑"><i class="icon-common-edit icon-pencil"></i></a>

上面的代码是我们最终的效果,表示这个超链接是有在用户具有claim(type=goods,value=edit)权限的时候才显示,下面我们就来介绍如何实现这个taghelper。

1)首先我们定义一个类,派生自taghelper类,并增加claim属性定义,并增加viewcontext

class claimtaghelper:taghelper
{
private const string claimattributename = "asp-claim";
    public claimtaghelper()
    {
    }
    [htmlattributename(claimattributename)]
    public string claim { get; set; }
}

2)我们的权限控制taghelper只运用于button,a,input的元素上,所有我们需要加上htmltargetelement的特性,代码如下:

[htmltargetelement("a", attributes = claimattributename)]
  [htmltargetelement("button", attributes = claimattributename)]
  [htmltargetelement("input", attributes = claimattributename, tagstructure = tagstructure.withoutendtag)]
  public class claimtaghelper: taghelper
{
......
}

3)重写taghelper的process方法,在方法中使用httpcontext.user.hasclaim进行权限判断。在视图中访问httpcontext必须借助于viewcontext对象,所以我们需要在当前的taghelper类中增加viewcontext引用,具体代码如下:

public class claimtaghelper: taghelper
{
.....

[htmlattributenotbound]
    [viewcontext]
    public viewcontext viewcontext { get; set; } 
.....
}

基本条件都具备了,然后就是process实现,直接上代码:

public override void process(taghelpercontext context, taghelperoutput output)
    {
      if (string.isnullorempty(claim))
      {
        return;
      }
      string[] claimdata = claim.split(new char[] { '-' }, stringsplitoptions.removeemptyentries);
      if (claimdata.length == 1)
      {
        if (!viewcontext.httpcontext.user.hasclaim(m => m.type == claimdata[0]))
        {
          //无权限
          output.suppressoutput();
        }
      }
      else
      {
        if (!viewcontext.httpcontext.user.hasclaim(m => m.type == claimdata[0] && m.value == claimdata[1]))
        {
          //无权限
          output.suppressoutput();
        }
      }
}

到这里就介绍完了,谢谢大家,如有不足之处,欢迎大家指导。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网