2013-04-17 66 views
0
public class CheckoutController : Controller 
{ 
    string userID; 

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

當我運行上面的代碼,我得到這個錯誤,Asp.net MVC4,控制器構造

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

在這一類中,大多數方法需要一個用戶ID,所以我要定義值在構造函數中,我該如何解決這個問題?

[編輯]

public class CheckoutController : Controller 
{ 
    string userID; 

    public CheckoutController() 
    { 
     //None 
    } 
} 

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

+2

你確定這就是路由呼叫控制器?它看起來像你已經有一個無參數的構造函數。 – DavGarcia

+0

如果是這樣,你最近是否重建過你的代碼?它可能已過時... –

+0

@Expert,因爲它是開箱即用的,只有無參數的構造函數可以工作'public CheckoutController()',但是您想使用'public CheckoutController(int userId)'? – Jasen

回答

3

執行流水線相關的值(RequestResponse,和User)被綁定ONLY AFTERController的構造方法。這就是爲什麼你不能使用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不會消極,因爲它已經從FormsAuthentication餅乾由ASP.NET運行時解密(假設你使用FormsAuthentication爲Web應用程序)的性能影響。

所以不要費心將它緩存到類成員變量。

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(); 
    } 
} 
+1

僅供參考,該圖表是過時的,我認爲它是針對MVC1的Pre-CTP1,事情發生了一些變化。有一個更好的一個在這裏引用http://blog.stevensanderson.com/2009/10/08/aspnet-mvc-learning-resource-request-handling-pipeline-poster/ –

+0

謝謝你們倆。另外,爲了提供更好的鏈接,我提交了一個編輯。只是在情況下:http://i.imgur.com/96jp1eu.png – SgtPooki