1

I have Mvc5 project and i m using Owin.

Im getting Authentication from OwinContext,

private IAuthenticationManager AuthenticationManager
{ 
    get
    {
        return HttpContext.GetOwinContext().Authentication;
    }
}

and AuthenticationManager makes user sign in.

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);

    Session_Add(user);

}

Here is my call in HomeController. I m trying to login after facebook callback.

public ActionResult Index()
{
    try
    {
        if (Request.QueryString["code"] != null)
        {
            string code = Request.QueryString["code"].ToString();
            string state = "";
            string type = "";
            var fb = new FacebookController();
            var me = fb.GetUserInfo(fb.GetAccessToken(code, state, type));
            new AccountController().LookUserFromFacebook(me);
        }

        return View();
    }
    catch
    {
        return View();
    }
}

When login form submit to AccountController user can do login. But the problem if i call SignInAsync method from another controller, HttpContext always return null. I think, it because of this call not a request so controller doesn't create a context.

What is the solution for if i call SignInAsync.

Thx.

erkan demir
  • 1,386
  • 4
  • 20
  • 38

1 Answers1

2

You can't use controllers like you do. Controllers are end-points in MVC application. If you need to execute an operation from 2 different end-points, wrap that code in a service class and call that code from both of your controllers.

Don't ever do var controller = new AcctountController() - this will give you not-initialised object that will not operate correctly. Best is to leave controller initalisation to the framework, or in the worst case scenario you can use ControllerFactory, but I highly discourage from this.

trailmax
  • 34,305
  • 22
  • 140
  • 234