3

I was trying to set a property in the constructor af a controller like this:

public ApplicationUserManager UserManager { get; private set; }
public AccountController()
    {
        UserManager = HttpContext.GetOwinContext().Get<ApplicationUserManager>("");
    }

But as explained here:

https://stackoverflow.com/a/3432733/1204249

The HttpContext is not available in the constructor.

So how can I set the property so that I can access it in every Actions of the Controller?

4

1 回答 1

5

您可以将代码移动到控制器上的只读属性中(或者如果您需要它在整个应用程序中可用,则可以将其移动到基本控制器中):

public class AccountController : Controller {
    private ApplicationUserManager userManager;

    public ApplicationUserManager UserManager {
        if (userManager == null) {
            //Only instantiate the object once per request
            userManager = HttpContext.GetOwinContext().Get<ApplicationUserManager>("");
        }

        return userManager;
    }
}
于 2014-06-21T15:23:42.710 回答