繁体   English   中英

异步调用后 UserContext 变为 null

[英]UserContext becomes null after async call

我在 function Verify中有一个 web 服务调用。 代码如下:

public async Task<ActionResult> Index()
{
    ....
    
    UserContext.LoginUser = null;

    if (!string.IsNullOrEmpty(etoken))
    {
        SSOLogin ssoLogin = new SSOLogin();
        LoginUser user = await ssoLogin.Verify(etoken);
        UserContext.LoginUser = user;
        if (UserContext.LoginUser == null)
            return RedirectToAction("UnAuthorized", "Login");
        else
        {
            Session["authenticated"] = true;
            userId = UserContext.LoginUser.UserId;
            domain = UserContext.LoginUser.Domain;
        }
    }
}

public async Task<LoginUser> Verify(string etoken)
{
    string publicKey = "xxx";

    LoginUser loginUser = null;

    WSVerifyAccessToken wsVerifyAccessToken = new WSVerifyAccessToken();
    string verifyResponse = await wsVerifyAccessToken.VerifyAccessToken(etoken); // Inside, this is a web service call

    if (!string.IsNullOrEmpty(verifyResponse))
    {
        /* Some processing here */
    }


    return loginUser;
}

问题是,在Verify function 之后,UserContext 变为 null

LoginUser user = await ssoLogin.Verify(etoken);

因此,当我分配

UserContext.LoginUser = user;

给我错误System.NullReferenceException: Object reference not set to an instance of an object. .

我试图使 function 同步

LoginUser user = await ssoLogin.Verify(etoken).Result;

但随后 web 服务调用将挂在那里并且永远不会结束。

有什么解决办法吗?

当 web.config 文件中的运行时目标框架为 4.0 而不是 4.5 或更高版本时,这是一个已知问题。 这可能与您的项目设置的目标框架不同。 确保运行时目标框架为 4.5 或更高版本

另外: UserContext 绑定到初始化请求的线程。 因此,您应该将等待调用的回调返回到原始上下文。 即使 ConfigureAwait(true) 是默认值,您也应该通过指定以下内容来确保在回调中使用正确的上下文:

UserContext.LoginUser = await ssoLogin.Verify(etoken).ConfigureAwait(true);

在此处查看有关配置等待方法的更详细说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM