3

我是 ASP.NET MVC 的新手,

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

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

4

1 回答 1

8

User您从控制器中使用的对象User.Identity.GetUserId()HttpContext.User.

HttpContext您可以通过使用HttpContext.Currentwhich sits within来获取电流System.Web

您还需要 Extension 方法的 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();
    }
}

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

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

于 2016-01-04T10:33:28.207 回答