解决用户代码处理的NullValueException [英] Solve NullValueException handled by user code

查看:69
本文介绍了解决用户代码处理的NullValueException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

下面是我正在使用的代码.我想从集合中检索用户名和名称.谁能告诉我从NameValueCollection检索ID和名称的正确方法是什么.

Hello

Below is the code that I am using. I want to retrieve the userid and name from collection. Can anyone tell me what is correct method of retrieve id and name from the NameValueCollection.

private void HandleAuthorizeTokenResponse()
    {
        string consumerKey = ConfigurationManager.AppSettings["googleConsumerKey"];
        string consumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"];
        string token = Request.QueryString["oauth_token"];
        string verifier = Request.QueryString["oauth_verifier"];
        string accessTokenEndpoint = "https://www.google.com/accounts/OAuthGetAccessToken";

        // Exchange the Request Token for an Access Token
        var oAuthConsumer = new OAuthConsumerNew();

        var accessToken = oAuthConsumer.GetOAuthAccessToken(accessTokenEndpoint, realm, consumerKey, consumerSecret, token, verifier, GetRequesttoken().TokenSecret);

        // Google Only - This method will get the email of the authenticated user
        var responseText = oAuthConsumer.GetUserInfo("https://www.googleapis.com/oauth2/v1/userinfo?alt=json", realm, consumerKey, consumerSecret, accessToken.Token, accessToken.TokenSecret);
        string queryString = responseText;
   
        NameValueCollection nvc = StringToValue(queryString.Replace("\"", ""));
        string userid = string.Empty;
        string name = string.Empty;
        
        if (nvc["id"] != "")
        {
            userid = nvc["id"].ToString();
            // NullValueException handled by user code
            name = nvc["name"].ToString();
              // NullValueException handled by user code
            Response.Write("Userid" + userid + "<br />");
            Response.Write("FName=" + name + "<br />");
        }
    }


NameValueCollection StringToValue(string queryString)
    {
        NameValueCollection queryParameters = new NameValueCollection();
        string[] querySegments = queryString.Split(',');
        foreach (string segment in querySegments)
        {
            string[] parts = segment.Split(':');
            if (parts.Length > 0)
            {
                string key = parts[0].Trim(new char[] { '?', ' ' });
                string val = parts[1].Trim();
                Response.Write(key + ":" + val);
                queryParameters.Add(key, val);
            }
        }
        return queryParameters;
    }




谢谢,
Deepak




Thanks,
Deepak

推荐答案

确定:这行不通-甚至都无法编译.

OK: that isn''t going to work - it isn''t even going to compile.

string queryString = {"id": "1234", "name": "ABC XYZ", "given_name": "ABC", "family_name": "XYZ", "link": "http://profiles.google.com/123456", "gender": "male", "locale": "en-GB"};

会给您带来大量错误-首先是您只能在数组上使用数组初始化器.如果要将其初始化为单个字符串(并且我假设您要进行测试),则需要:

will give you a huge pile of errors - the first being that you can only use an array initializer on an array. If you want to initialize this as a single string (and I assume you are for testing) then you need:

string queryString = "\"id\": \"1234\",...";

其中"..."是您的其余字符串的类似处理方式.那可能会解决您的主要问题.
然后,您的下一个问题是您的字符串同时包含:"作为定界符和:"作为字符串的一部分-请查看"http ..."部分.
如果您的字符串将始终为格式

Where "..." is the rest of your string similarly handled. That will probably fix your main problem.
Then, your next problem is that your string contains both '':'' as a delimiter, and '':'' as a part of your string - look at the "http..." part.
If your string will always be of the form

"key":"value"

用逗号分隔,我很想使用正则表达式而不是手动处理:

separated by commas, I would be tempted to use a Regex instead of manual processing:

public static Regex regex = new Regex("(?:\")(?<Key>.*?)(?:\")\\s*:\\s*(?:\")(?<Value>.*?)(?:\")",
    RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);


MatchCollection可以为您提供所需的组.



您能给我完整的代码吗,请尝试通过在您的代码中混合您的代码来为我提供完美的解决方案.我很困惑应该在哪里使用您的代码来获得理想的结果"

您的最后一个奴隶死于什么? :laugh:


The MatchCollection for this should give you the groups you want.



"can you me the complete code . Try to give me perfect solution by mixing your code in my code. I got confused where should I use your code to get the desired result"


What did your last slave die of? :laugh:

        public static Regex regex = new Regex("(?:\")(?<Key>.*?)(?:\")\\s*:\\s*(?:\")(?<Value>.*?)(?:\")",
                                              RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
...
            string queryString = "\"id\": \"1234\", \"name\": \"ABC XYZ\", \"given_name\": \"ABC\", \"family_name\": \"XYZ\", \"link\": \"http://profiles.google.com/123456\", \"gender\": \"male\", \"locale\": \"en-GB\"";
            MatchCollection matches = regex.Matches(queryString);
            NameValueCollection queryParameters = new NameValueCollection();
            foreach (Match match in matches)
                {
                queryParameters.Add(match.Groups["Key"].Value, match.Groups["Value"].Value);
                }


这篇关于解决用户代码处理的NullValueException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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