null-coalescing运算符如何导致错误?

时间:2016-03-02 07:02:12

标签: c# asp.net-mvc oauth-2.0

这很奇怪。

这与文章"将OAuth 2.0与Web应用程序一起使用(ASP.NET MVC)":https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web-applications-aspnet-mvc

忽略整个代码,不需要,问题是这个 - 有一个方法:

public class AppFlowMetadata : FlowMetadata
{
    private static string userId;

    public override string GetUserId(Controller controller)
    {
        if (userId == null)
        {
            userId = Guid.NewGuid().ToString();
        }
        return userId;
    }
}

就像一个魅力,永远不会失败

奇怪的是 - 如果我使用null-coalescing运算符(??)而不是IF块:

    public override string GetUserId(Controller controller)
    {
        return userId ?? Guid.NewGuid().ToString();
    }

经常失败,抛出异常:

  

Google.Apis.Auth.OAuth2.Responses.TokenResponseException:   错误:" invalid_grant",说明:"代码无效。",Uri:""

老实说,我相信这两个代码必须具有相同的效果。根据MSDN:

  

?? operator被称为null-coalescing运算符。它返回   如果操作数不为空,则为左操作数;否则它返回   右手操作。

有人可以向我解释一下吗? :)

更新我的不好,确实在第二段代码中没有为userId分配新的Guid。它应该是这样的:

userId = userId ?? Guid.NewGuid().ToString();
return userId;

1 个答案:

答案 0 :(得分:6)

这两种方法不一样。

第一个将在每次调用时返回相同的GUID(只要userID未在其他位置设置)。

第二个会在每次调用时返回不同的GUID(除非userID在其他地方设置为null)。