【问题标题】:Difference between HttpContext.Current.User and this.User.IdentityHttpContext.Current.User 和 this.User.Identity 之间的区别
【发布时间】:2015-09-10 10:18:43
【问题描述】:

HttpContext.Current.User.Identity.IsAuthenticatedthis.User.Identity.IsAuthenticated 有什么区别?有时它们会出现在我的代码中,有时它们不会出现(所以我必须使用另一个)。它们的意思是一样的还是应该有特定的“上下文”供我使用?

我有我在我的一个班级中使用的这段代码:

if (!HttpContext.Current.User.Identity.IsAuthenticated) {

    return 0;

}

那么 thisHttpContext 是什么?我知道this 指的是一个特定的实例,但是HttpContext 呢?

【问题讨论】:

  • 将鼠标悬停在this / HttpContext 上,单击鼠标右键,转到定义
  • 它是开源的,所以你应该检查代码。它们应该是一样的。
  • 哦,好的,谢谢大家。

标签: c# asp.net-mvc


【解决方案1】:

HttpContext.Current.User.Identity.IsAuthenticatedthis.User.Identity.IsUthenticated 是同一个东西,但用法不同。

你使用 this.User.Identity.IsUthenticated 在控制器内,但是 如果您在控制器之外并且您需要知道用户是否经过身份验证,您可以使用HttpContext.Current.User.Identity.IsAuthenticated

【讨论】:

  • 上下文可能会返回 null,因此请注意。
  • 是否有理由不在控制器中使用HttpContext. 而不是this.
【解决方案2】:

完全没有区别。 HttpContext.Current.User 和 Controller.User 都是一样的。

“this”是你的Controller,BaseController有User属性。

事情是这样的。

 public class Controller
 {
      public User { get { return HttpContext.Current.User; } }
 }

 public class YourController : Controller
 {
      public ActionResult Index()
      {
           return this.User.Identity.Name;
      }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2021-12-25
    • 2020-05-10
    • 2014-09-20
    • 2010-10-28
    • 2015-10-04
    • 2012-08-12
    相关资源
    最近更新 更多