Expert wanna be
Expert wanna be

Reputation: 10624

Asp.net MVC4, Controller constructor

public class CheckoutController : Controller
{
    string userID;

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

When I run the above code, I get this error,

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

In that class, most of method need that userID, so I want to define that value in constructor, how can I solve this problem?

[Edit]

public class CheckoutController : Controller
{
    string userID;

    public CheckoutController()
    {
      //None
    }
}

This code works fine, no error.

Upvotes: 0

Views: 3087

Answers (1)

stun
stun

Reputation: 1744

Execution pipeline related values (Request, Response, and User) are binded ONLY AFTER the Controller's constructor method. That is why you can't use User.Identity as it is not binded yet. Only after the Step 3: IController.Execute() is when those contextual values are initialized.

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

Updated Poster: link to a newer poster based on @mystere-man's feedback thanks to @SgtPooki. But I am keeping the older embeddable image in here to make it a bit easier to reference.

ASP.NET MVC Pipeline

User.Identity.Name does not negatively affect the performance as it has already been decrypted from the FormsAuthentication cookie by the ASP.NET runtime (assuming you are using FormsAuthentication for your web application).

So don't bother caching it to a class member variable.

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

Upvotes: 3

Related Questions