【问题标题】:Call User.Identity.GetUserId() from Helpers with ASP.NET MVC使用 ASP.NET MVC 从 Helpers 调用 User.Identity.GetUserId()
【发布时间】:2016-01-04 10:22:23
【问题描述】:

我是 ASP.NET MVC 的新手,

我将一个 HTTP POST 方法从我的控制器移到了 Helpers,但我无法从 System.Security.Principal.IIdentity 库中调用 User.Identity.GetUserId()

为什么我不能从助手中使用这个库?谢谢

【问题讨论】:

  • 你能显示一些代码吗?

标签: c# asp.net-mvc asp.net-mvc-helpers


【解决方案1】:

您使用User.Identity.GetUserId() 从控制器中获取的User 对象是HttpContext.User 类型。

您可以使用位于System.Web 中的HttpContext.Current 获取当前的HttpContext

您还需要扩展方法的 using 语句。

using Microsoft.AspNet.Identity;
using System.Web;

public class MyClass()
{
    public void MyMethod()
    {
        // Get the current context
        var httpContext = HttpContext.Current;

        // Get the user id
        var userId = httpContext.User.Identity.GetUserId();
    }
}

如果您在辅助方法中检索此值,我个人建议将其作为参数从您的控制器传入,因为这样可以更清楚地表明它依赖于它?

如果您将辅助方法移动到服务层等中,您将需要从控制器中获取此值并将其作为参数传递。

【讨论】:

  • 谢谢伙计,我知道我打的电话不对。我会听从你的建议。再次感谢
猜你喜欢
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
相关资源
最近更新 更多