小编use*_*440的帖子

从控制器的构造函数运行异步方法时出现问题

我正在开发一个项目,我想让用户使用访问令牌/刷新令牌登录.我将这些值存储在cookie中,每当用户访问该站点时,无论用于访问该站点的页面如何,我都希望自动登录.为此,我创建了一个BaseController,所有其他控制器都继承自.BaseController看起来像这样:

public abstract class BaseController : Controller
{
    public BaseController()
    {
        LoginModel.SetUserFromAuthenticationCookie();
    }
}
Run Code Online (Sandbox Code Playgroud)

每次执行操作之前都会执行此构造函数,因此正是我想要的.问题是这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());
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

问题是执行顺序不是我预期的,因此用户没有登录.我试图使用 …

asp.net-mvc asynchronous async-await

6
推荐指数
1
解决办法
2693
查看次数

标签 统计

asp.net-mvc ×1

async-await ×1

asynchronous ×1