失去的HttpContext与异步伺机在ASP​​.NET身份GetRolesAsync [英] Losing HttpContext with async await in ASP.NET Identity GetRolesAsync

查看:213
本文介绍了失去的HttpContext与异步伺机在ASP​​.NET身份GetRolesAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是超过ASP.NET身份异步/的await问题。我使用Asp.Net的身份,并有一个自定义UserStore,用定制的GetRolesAsync方法。该的UserManager从控制器的WebAPI调用。

This is more of an async/await question than ASP.NET Identity. I am using Asp.Net Identity, and have a custom UserStore, with a customized GetRolesAsync method. The UserManager is called from a WebApi controller.

public class MyWebApiController {
    private MyUserManager manager = new MyUserManager(new MyUserStore());
    [HttpGet]
    public async Task<bool> MyWebApiMethod(int x) {
        IList<string> roles = await manager.GetRolesAsync(x);
        return true;
    }
}
public class MyUserManager : UserManager<MyUser, int> {

    // I do not implement a custom GetRolesAsync in the UserManager, but 
    // from looking at the identity source, this is what the base class is doing:

    // public virtual async Task<IList<string>> GetRolesAsync(TKey userId)
    // {
    //     ThrowIfDisposed();
    //     var userRoleStore = GetUserRoleStore();
    //     var user = await FindByIdAsync(userId).WithCurrentCulture();
    //     if (user == null)
    //     {
    //         throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,userId));
    //     }
    //     return await userRoleStore.GetRolesAsync(user).WithCurrentCulture();
    // }
}

public class MyUserStore {
    public async Task<IList<string>> GetRolesAsync(TUser user) {

        // I need HttpContext here and it is NULL. WHY??
        var currentContext = System.Web.HttpContext.Current; // NULL!

         var query = from userRole in _userRoles
                    where userRole.UserId.Equals(userId)
                    join role in _roleStore.DbEntitySet on userRole.RoleId equals role.Id
                    select role.Name;

        return await query.ToListAsync();
    }
}

为什么是空的上下文中MyUserStore.GetRolesAsync?我想伺机传递的上下文下来?我已经通过其他异步方法介入MyUserStore,他们都具有正确的上下文,code看起来几乎相同。

Why is context null in MyUserStore.GetRolesAsync? I thought await passed the context down? I've stepped through other async methods in MyUserStore and they all have the correct context, and the code seems virtually identical.

推荐答案

这原来是 TaskExtensions.WithCurrentCulture 的属性。这些都是文档为EF,但它们适用于ASP.NET身份,以及:

This turns out to be a property of TaskExtensions.WithCurrentCulture. These are the docs for EF, but they apply for ASP.NET Identity as well:

配置用来等待这个任务以避免编组继续回到原来的环境的awaiter,但preserve当前文化和UI文化。

Configures an awaiter used to await this Task to avoid marshalling the continuation back to the original context, but preserve the current culture and UI culture.

这会导致同步上下文不是元帅,这将导致的HttpContext

This causes the synchronization context not to marshal, which causes HttpContext to be null.

下面是相关的部分从<一个href=\"https://www.symbolsource.org/MyGet/Metadata/aspnetwebstacknightly/Project/Microsoft.AspNet.Identity.Core/2.2.0-alpha1-140802/Release/Default/Microsoft.AspNet.Identity.Core/Microsoft.AspNet.Identity.Core/TaskExtensions.cs?ImageName=Microsoft.AspNet.Identity.Core\"相对=nofollow>来源:

public void UnsafeOnCompleted(Action continuation)
{
    var currentCulture = Thread.CurrentThread.CurrentCulture;
    var currentUiCulture = Thread.CurrentThread.CurrentUICulture;

    // This part is critical.
    _task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(() =>
    {
        var originalCulture = Thread.CurrentThread.CurrentCulture;
        var originalUiCulture = Thread.CurrentThread.CurrentUICulture;
        Thread.CurrentThread.CurrentCulture = currentCulture;
        Thread.CurrentThread.CurrentUICulture = currentUiCulture;
        try
        {
            continuation();
        }
        finally
        {
            Thread.CurrentThread.CurrentCulture = originalCulture;
            Thread.CurrentThread.CurrentUICulture = originalUiCulture;
        }
    });
}

这篇关于失去的HttpContext与异步伺机在ASP​​.NET身份GetRolesAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆