1

尝试获取给定站点的 cookie 时,我遇到了这个奇怪的异常。该CookieContainer对象是单例类的成员,因此应用程序中的每个 HttpWebRrequest 都可以访问站点的身份验证 cookie。

    public string GetXsrfToken(string url)
    {
        Uri u = new Uri(url);
        CookieCollection cc;
        try
        {
            cc = this.Cookies.GetCookies(u);
        }
        catch
        {
            cc = this.Cookies.GetCookies(u);
        }

        string token =string.Empty;
        foreach (Cookie c in cc)
        {
            if (c.Name == "atlassian.xsrf.token")
            {
                token = c.Value;
                break;
            }
        }

        return token;
    }

完整课程可在http://pastebin.com/QaDSs2g5获得。
第一次调用GetCookiesthrows aArgumentOutOfRangeException并带有以下堆栈跟踪:

at System.DateTime.Add(Double value, Int32 scale)
at System.TimeZoneInfo.TransitionTimeToDateTime(Int32 year, TransitionTime transitionTime)
at System.TimeZoneInfo.GetDaylightTime(Int32 year, AdjustmentRule rule)
at System.TimeZoneInfo.GetIsDaylightSavingsFromUtc(DateTime time, Int32 Year, TimeSpan utc, AdjustmentRule rule, Boolean& isAmbiguousLocalDst)
at System.TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(DateTime time, Boolean& isAmbiguousLocalDst)
at System.DateTime.get_Now()
at System.Net.CookieCollection.TimeStamp(Stamp how)
at System.Net.CookieContainer.InternalGetCookies(Uri uri)
at System.Net.CookieContainer.GetCookies(Uri uri)
at JiraVersionSync.Core.CookieMgr.GetXsrfToken(String url) in C:\JIRA\dev\JiraVersionSync\JiraVersionSync.Core\CookieMgr.cs:line 46

中导致此异常的参数DateTime.Addvalue,即null

但是第二次调用完美无缺,然后我就可以找到我想要的 cookie 并且它的价值。所以我的代码有效,但我觉得它很难看,我很好奇为什么它第一次失败。任何想法,有人?

4

0 回答 0