我应该如何检查用户是否在MVC5中进行了身份验证

我应该如何检查用户是否在MVC5中进行了身份验证

本文介绍了我应该如何检查用户是否在MVC5中进行了身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过以下两个可访问的布尔值:

I have seen the following two accessible booleans:

  • System.Web.Mvc.Controller.User.Identity.IsAuthenticated
  • System.Web.Mvc.Controller.Request.IsAuthenticated
  • System.Web.Mvc.Controller.User.Identity.IsAuthenticated
  • System.Web.Mvc.Controller.Request.IsAuthenticated

这些之间是否有区别.他们俩似乎都在做同一件事,所以我不确定该使用哪个.

Is there a difference between these. They both seem to do the same thing so I am not sure which to use.

我想做的是:

@if (User.Identity.IsAuthenticated) {
  if (User.IsInRole("Admin")) {
    @Html.ActionLink("Admin", "AdminController")
  }
}

@if (Request.IsAuthenticated) {
  if (User.IsInRole("Admin")) {
    @Html.ActionLink("Admin", "AdminController")
  }
}

以上两种方法都能很好地工作吗?

Would either of the above work equally well ?

推荐答案

没有区别.唯一的区别是,如果用户未通过身份验证,则User.Identity可能为null,因此您可能会获得NRE,而使用第二种方法时,内部会对此进行检查并且更加安全.

There's no difference. The only difference is that if the user is not authenticated User.Identity might be null and thus you might get a NRE, whereas with the second approach, internally there's a check for this and is safer.

Request.IsAuthenticated方法的实现方式如下:

Here's how the Request.IsAuthenticated method is implemented:

public bool IsAuthenticated
{
    get
    {
        return this._context.User != null &&
               this._context.User.Identity != null &&
               this._context.User.Identity.IsAuthenticated;
    }
}

基本上,它比第一个要安全一些.

Basically it's a bit safer than the first one.

这篇关于我应该如何检查用户是否在MVC5中进行了身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:06