簡體   English   中英

Asp.net MVC4,控制器構造函數

[英]Asp.net MVC4, Controller constructor

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
    }
}

這段代碼工作正常,沒有錯誤。

與執行管道相關的值( RequestResponseUserController的構造方法之后綁定。 這就是為什么您不能使用User.Identity因為它尚未綁定。 僅在步驟3: IController.Execute()之后,才初始化這些上下文值。

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

更新的海報: 感謝@ mystere-man的反饋,感謝@SgtPooki鏈接到更新的海報 但是我將較舊的可嵌入圖像保留在此處,以使其易於參考。

ASP.NET MVC管道

User.Identity.Name不會對性能產生負面影響,因為它已經由ASP.NET運行時從FormsAuthentication cookie中解密( 假設您正在對Web應用程序使用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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM