[英]Mvc5 HttpContext return null
I have Mvc5 project and im using Owin. 我有Mvc5项目,我正在使用Owin。
Im getting Authentication from OwinContext
, 我从
OwinContext
获得身份验证,
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
and AuthenticationManager
makes user sign in. 而
AuthenticationManager
使用户登录。
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. 这是我在HomeController中的电话。 I m trying to login after
facebook
callback. 我正在尝试在
facebook
回调后登录。
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. 登录表单提交到
AccountController
用户可以登录。 But the problem if i call SignInAsync
method from another controller, HttpContext
always return null. 但是如果我从另一个控制器调用
SignInAsync
方法,则HttpContext
总是返回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
. 如果我致电
SignInAsync
该如何解决?
Thx. 谢谢。
You can't use controllers like you do. 您不能像使用控制器那样使用控制器。 Controllers are end-points in MVC application.
控制器是MVC应用程序中的端点。 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.
如果需要从2个不同的端点执行操作,则将该代码包装在服务类中,然后从两个控制器中调用该代码。
Don't ever do var controller = new AcctountController()
- this will give you not-initialised object that will not operate correctly. 永远不要做
var controller = new AcctountController()
-这将使您无法初始化的对象无法正常运行。 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. 最好是将控制器初始化留在框架中,或者在最坏的情况下,您可以使用
ControllerFactory
,但是我强烈不建议这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.