Asp.net mvc 从控制器运行异步方法时出现问题';s构造函数
我正在从事一个项目,希望让用户使用访问令牌/刷新令牌登录。我将这些值存储在cookie中,每当用户访问该站点时,我都希望自动让他登录,而不管他使用哪个页面访问该站点。为此,我创建了一个BaseController,所有其他控制器都从中继承。BaseController如下所示:Asp.net mvc 从控制器运行异步方法时出现问题';s构造函数,asp.net-mvc,asynchronous,async-await,Asp.net Mvc,Asynchronous,Async Await,我正在从事一个项目,希望让用户使用访问令牌/刷新令牌登录。我将这些值存储在cookie中,每当用户访问该站点时,我都希望自动让他登录,而不管他使用哪个页面访问该站点。为此,我创建了一个BaseController,所有其他控制器都从中继承。BaseController如下所示: public abstract class BaseController : Controller { public BaseController() { LoginModel.SetUs
public abstract class BaseController : Controller
{
public BaseController()
{
LoginModel.SetUserFromAuthenticationCookie();
}
}
public async static Task SetUserFromAuthenticationCookie()
{
// Check if the authentication cookie is set and the User is null
if (AuthenticationRepository != null && User == null)
{
Api api = new Api();
// If a new authentication cookie was successfully created
if (await AuthenticationRepository.CreateNewAuthenticationCookieAsync())
{
var response = await api.Request(HttpMethod.Get, "api/user/mycredentials");
if(response.IsSuccessStatusCode)
{
User = api.serializer.Deserialize<UserViewModel>(await response.Content.ReadAsStringAsync());
}
}
}
}
每次执行操作之前都会执行此构造函数,因此这正是我想要的。问题在于SetUserFromAuthenticationCookie()
是一个异步方法,因为它必须调用其他异步方法。看起来是这样的:
public abstract class BaseController : Controller
{
public BaseController()
{
LoginModel.SetUserFromAuthenticationCookie();
}
}
public async static Task SetUserFromAuthenticationCookie()
{
// Check if the authentication cookie is set and the User is null
if (AuthenticationRepository != null && User == null)
{
Api api = new Api();
// If a new authentication cookie was successfully created
if (await AuthenticationRepository.CreateNewAuthenticationCookieAsync())
{
var response = await api.Request(HttpMethod.Get, "api/user/mycredentials");
if(response.IsSuccessStatusCode)
{
User = api.serializer.Deserialize<UserViewModel>(await response.Content.ReadAsStringAsync());
}
}
}
}
如果我随后将BaseController构造函数的内容更改为:
AsyncHelpers.RunSync(() => LoginModel.SetUserFromAuthenticationCookie());
该功能按预期工作
不过,我想知道你是否有任何关于如何更好地做到这一点的建议。也许我应该将对SetUserFromAuthenticationCookie()的调用移动到另一个位置,但此时我不知道该调用在哪里。我在另一个堆栈上找到了此解决方案 您的构造函数需要如下所示
public BaseController()
{
var task = Task.Run(async () => { await LoginModel.SetUserFromAuthenticationCookie(); });
task.Wait();
}
您不会使用
wait LoginModel.SetUserFromAuthenticationCookie()代码>?或LoginModel.SetUserFromAuthenticationCookie().RunSynchronously()代码>我无法回答有关异步的问题。。。但是如果您希望在每次操作之前执行此代码,您可以考虑创建全局动作筛选器。@ JAMIDE77,我不能等待构造函数,这就是问题所在。而且RunSynchronously()不执行此任务。是的,您仍然必须同步运行它。我只是说操作过滤器可能比构造函数更适合放置它。我不知道我可以在任务的Run函数中使用async/await。谢谢你的提醒!我现在遇到的问题是,对于某些部分,我依赖于HttpContext.Current.xxx,并且在新创建的线程HttpContext.Current(显然)为null。我已经在计划重构代码的这些部分,现在将开始着手这方面的工作。等我说完,知道你的建议是否解决了我的问题后,我会回到这个问题上来。谢谢你迄今为止的帮助!