获取System.Threading.Tasks.Task(ApplicationUser MVC)的结果

时间:2016-12-19 18:28:59

标签: multithreading asp.net-core asp.net-core-mvc

我只是想在MVC中获取我的ApplicationUser。我正在尝试这段代码:

    public async System.Threading.Tasks.Task<ApplicationUser> GetApplicationUser()
    {
        return await _userManager.GetUserAsync(HttpContext.User); 
    }

    var user = GetApplicationUser(); 
    var user2 = user.Result; 

然而,当我尝试访问user.Result时,我得到异常

"One or more errors occurred. (Object reference not set to an instance of an object.)"
"Object reference not set to an instance of an object."

不确定如何访问结果。

3 个答案:

答案 0 :(得分:0)

根据您发布的代码(没有任何异常详情),我会猜测问题是_userManagernull

但是,如果你解决了这个问题,你会遇到另一个问题。具体来说,您应该使用await而不是Result; the latter can cause deadlocks

答案 1 :(得分:0)

确保您的控制器操作是异步任务,如下所示:

    public async Task<IActionResult> Test()
    {            
        ApplicationUser user = await GetCurrentUserAsync();
        if (user != null) {
            // do more stuff here
        }
        // do more stuff here
        return View();             
    }

    private Task<ApplicationUser> GetCurrentUserAsync()
    {
        return _userManager.GetUserAsync(HttpContext.User);
    }

答案 2 :(得分:-2)

我必须手动调用.Wait()函数,然后我才能成功访问.Result。另外,我的HttpContext为null所以我必须在Index()中使用它,如

    public IActionResult Index()
    {
        DoSomethingWith(HttpContext);
        return View();
    }

            System.Threading.Tasks.Task<ApplicationUser> user = GetApplicationUser(context); 
            user.Wait(); 
            var user2 = user.Result;