Asp.net MVC4,Controller构造函数

时间:2013-04-17 19:23:27

标签: asp.net-mvc-4

public class CheckoutController : Controller
{
    string userID;

    public CheckoutController()
    {
        userID = User.Identity.Name;
    }
    ...
}

当我运行上面的代码时,我收到此错误,

**Make sure that the controller has a parameterless public constructor.**

在该类中,大多数方法都需要userID,所以我想在构造函数中定义该值,我该如何解决这个问题?

[编辑]

public class CheckoutController : Controller
{
    string userID;

    public CheckoutController()
    {
      //None
    }
}

此代码工作正常,没有错误。

1 个答案:

答案 0 :(得分:3)

与执行管道相关的值(RequestResponseUser)绑定仅在Controller的构造函数方法后。这就是为什么你不能使用User.Identity,因为它还没有绑定。只有在第3步:IController.Execute() 之后才会初始化这些上下文值。

http://blog.stevensanderson.com/blogfiles/2007/ASPNET-MVC-Pipeline/ASP.NET%20MVC%20Pipeline.jpg

更新海报: link to a newer poster based on @mystere-man's feedback thanks to @SgtPooki。但是我将旧的可嵌入图像保留在这里,以便更容易引用。

ASP.NET MVC Pipeline

User.Identity.Name不会对性能产生负面影响,因为它已经由ASP.NET运行时从FormsAuthentication cookie解密(假设您正在使用FormsAuthentication用于您的网络应用)。

所以不要把它缓存到类成员变量。

public class CheckoutController : Controller
{
    public CheckoutController() { /* leave it as is */ }

    public ActionResult Index()
    {
        // just use it like this
        string userName = User.Identity.Name;

        return View();
    }
}
相关问题