我正在处理一个项目,想要使用访问令牌/刷新令牌来保持用户的登录状态。我将这些值存储在cookie中,每当用户访问网站时,无论他使用哪个页面访问该网站,我都希望自动登录他。为此,我创建了一个BaseController,所有其他控制器都继承自该控制器。BaseController看起来像这样:
public abstract class BaseController : Controller
{
public BaseController()
{
LoginModel.SetUserFromAuthenticationCookie();
}
}
每次执行操作之前,都会执行此构造函数,这正是我想要的。问题在于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());
}
}
}
}
问题在于执行顺序不如预期,因此用户无法登录。我尝试使用异步方法的
.Result
,但结果导致死锁。除此之外,我阅读了许多关于该问题的SO线程,并最终找到一个成功使登录工作的线程:如何以同步方式运行异步Task<T>方法?。虽然这有点繁琐,但它可以通过这个辅助程序实现:public static class AsyncHelpers
{
/// <summary>
/// Execute's an async Task<T> method which has a void return value synchronously
/// </summary>
/// <param name="task">Task<T> method to execute</param>
public static void RunSync(Func<Task> task)
{
var oldContext = SynchronizationContext.Current;
var synch = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synch);
synch.Post(async _ =>
{
try
{
await task();
}
catch (Exception e)
{
synch.InnerException = e;
throw;
}
finally
{
synch.EndMessageLoop();
}
}, null);
synch.BeginMessageLoop();
SynchronizationContext.SetSynchronizationContext(oldContext);
}
/// <summary>
/// Execute's an async Task<T> method which has a T return type synchronously
/// </summary>
/// <typeparam name="T">Return Type</typeparam>
/// <param name="task">Task<T> method to execute</param>
/// <returns></returns>
public static T RunSync<T>(Func<Task<T>> task)
{
var oldContext = SynchronizationContext.Current;
var synch = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synch);
T ret = default(T);
synch.Post(async _ =>
{
try
{
ret = await task();
}
catch (Exception e)
{
synch.InnerException = e;
throw;
}
finally
{
synch.EndMessageLoop();
}
}, null);
synch.BeginMessageLoop();
SynchronizationContext.SetSynchronizationContext(oldContext);
return ret;
}
private class ExclusiveSynchronizationContext : SynchronizationContext
{
private bool done;
public Exception InnerException { get; set; }
readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false);
readonly Queue<Tuple<SendOrPostCallback, object>> items =
new Queue<Tuple<SendOrPostCallback, object>>();
public override void Send(SendOrPostCallback d, object state)
{
throw new NotSupportedException("We cannot send to our same thread");
}
public override void Post(SendOrPostCallback d, object state)
{
lock (items)
{
items.Enqueue(Tuple.Create(d, state));
}
workItemsWaiting.Set();
}
public void EndMessageLoop()
{
Post(_ => done = true, null);
}
public void BeginMessageLoop()
{
while (!done)
{
Tuple<SendOrPostCallback, object> task = null;
lock (items)
{
if (items.Count > 0)
{
task = items.Dequeue();
}
}
if (task != null)
{
task.Item1(task.Item2);
if (InnerException != null) // the method threw an exeption
{
throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);
}
}
else
{
workItemsWaiting.WaitOne();
}
}
}
public override SynchronizationContext CreateCopy()
{
return this;
}
}
如果我将BaseController构造函数的内容更改为:
如果我将BaseController的构造函数内容更改为:
AsyncHelpers.RunSync(() => LoginModel.SetUserFromAuthenticationCookie());
该功能按预期工作。
但我想知道是否有更好的方法来完成此操作。也许我应该将对SetUserFromAuthenticationCookie()
的调用移动到其他位置,但目前我不知道应该在哪里。
await LoginModel.SetUserFromAuthenticationCookie();
吗? - JamieD77LoginModel.SetUserFromAuthenticationCookie().RunSynchronously();
转换为中文: - JamieD77