【问题标题】:Impossible NullPointerException [closed]不可能的 NullPointerException [关闭]
【发布时间】:2016-05-20 18:27:11
【问题描述】:

我有一个 C# 程序并尝试使用静态方法读取 cookie:

[DllImport("wininet.dll", SetLastError = true)]
        public static extern bool InternetGetCookieEx(
        string url,
        string cookieName,
        StringBuilder cookieData,
        ref int size,
        Int32 dwFlags,
        IntPtr lpReserved);

        private const Int32 InternetCookieHttponly = 0x2000;

        /// <summary>
        /// Gets the URI cookie container.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns></returns>
        public static CookieContainer GetUriCookieContainer(Uri uri)
        {
            CookieContainer cookies = null;
            // Determine the size of the cookie
            int datasize = 8192 * 16;
            StringBuilder cookieData = new StringBuilder(datasize);
            if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
            {
                if (datasize < 0)
                    return null;
                // Allocate stringbuilder large enough to hold the cookie
                cookieData = new StringBuilder(datasize);
                if (!InternetGetCookieEx(
                    uri.ToString(),
                    null, cookieData,
                    ref datasize,
                    InternetCookieHttponly,
                    IntPtr.Zero))
                    return null;
            }
            if (cookieData.Length > 0)
            {
                cookies = new CookieContainer();
                cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
            }
            return cookies ?? new CookieContainer();
        }

代码来自这个answer

因此,如果 cookie 为空,我将返回一个不能为空的新 CookieContainer。

但是当我在我的应用程序中调用此方法时,返回值为 null。

var cookie = Util.GetUriCookieContainer(uri);

if (cookie == null)
 {
    MessageBox.Show("cookie is null");
 }

我错过了什么吗?

【问题讨论】:

  • 我在该方法中看到两条 return null; 行。如果您认为它永远不会null,那么这些行是干什么用的?
  • 使用调试器进行单步调试很容易找出问题所在。您应该在在这里提问之前尝试这样做(这可能是您获得如此多反对票的原因)。

标签: c# wpf nullpointerexception


【解决方案1】:

不能为空? 那是什么?

if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
{
    if (datasize < 0)
        return null;
    // Allocate stringbuilder large enough to hold the cookie
    cookieData = new StringBuilder(datasize);
    if (!InternetGetCookieEx(
            uri.ToString(),
            null, cookieData,
            ref datasize,
            InternetCookieHttponly,
            IntPtr.Zero))
        return null;
}

【讨论】:

    猜你喜欢
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多