0

Basically I get

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object occurred

when I try to get the token from the restservice.

when it gets to

public async Task<T> PostResponseLogin<T>(string weburl, FormUrlEncodedContent content) where T : class
        {
            var response = await client.PostAsync(weburl, content);
            var jsonResult = response.Content.ReadAsStringAsync().Result;
            var responseObject = JsonConvert.DeserializeObject<T>(jsonResult);
            return responseObject;
        }

on the return respondObject; it goes to the appDelegate and throws the exception.

-I'm currently in the learning process of C#/Xamarin, so if I have made a simple mistake that you notice, that will be why. Thanks for your help.

I've added MainPage = new NavigationPage(new LoginPage()); so I can navigate between pages, that is working.

edit: It was suggested that this might be a possible duplicate of another ticket with an unhandled exception. While it did help me to understand that error better, it's still more specific than that.

public class RestService
    {
        HttpClient client;
        string grant_type = "password";

        public RestService()
        {
            client = new HttpClient();
            client.MaxResponseContentBufferSize = 256000;
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded' "));
        }

        public async Task<Token> Login(User user)
        {
            var postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("grant_type", grant_type));
            postData.Add(new KeyValuePair<string, string>("Email", user.Email));
            postData.Add(new KeyValuePair<string, string>("Password", user.Password));
            var content = new FormUrlEncodedContent(postData);
            var weburl = "https://blahblah.com/auth/login";
            var response = await PostResponseLogin<Token>(weburl, content);
            DateTime dt = new DateTime();
            dt = DateTime.Today;
            response.expireDate = dt.AddSeconds(response.expireIn);
            return response;

        }

        public async Task<T> PostResponseLogin<T>(string weburl, FormUrlEncodedContent content) where T : class
        {
            var response = await client.PostAsync(weburl, content);
            var jsonResult = response.Content.ReadAsStringAsync().Result;
            var responseObject = JsonConvert.DeserializeObject<T>(jsonResult);
            return responseObject;
        }

        public async Task<T> PostResponse<T>(string weburl, string jsonstring) where T : class
        {
            var Token = App.TokenDatabase.GetToken();
            string ContentType = "application/json";
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Token.accessToken);
            try
            {
                var Result = await client.PostAsync(weburl, new StringContent(jsonstring, Encoding.UTF8, ContentType));
                if (Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var JsonResult = Result.Content.ReadAsStringAsync().Result;
                    try
                    {
                        var ContentResp = JsonConvert.DeserializeObject<T>(JsonResult);
                        return ContentResp;
                    }
                    catch { return null; }
                }


            }
            catch { return null; }
            return null;

        }

        public async Task<T> GetResponse<T>(string weburl) where T : class
        {
            var Token = App.TokenDatabase.GetToken();
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Token.accessToken);
            try
            {
                var response = await client.GetAsync(weburl);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var JsonResult = response.Content.ReadAsStringAsync().Result;
                    try
                    {
                        var ContentResp = JsonConvert.DeserializeObject<T>(JsonResult);
                        return ContentResp;
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
            catch
            {
                return null;
            }
            return null;




        }
    }
  • Can you check the response status code response.IsSuccessStatusCode. It is very important property which should be handled – ayon.gupta Apr 18 '19 at 06:05
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – FreakyAli Apr 18 '19 at 06:39
  • I guess your problem is in "PostResponseLogin" method. If you get an API error in your call this code should crash. I suggest debugging this method to see what is wrong. Are you 100% sure you have a correct API call? – lawiluk Apr 18 '19 at 06:48
  • So it looks like I wasn't getting a response from the api. I did at the response.IsSuccessStatusCode though. Thanks for telling me about that. I will considered this fixed unless it turns out I was wrong. – CaptainKirk Apr 19 '19 at 00:19
  • @KirkK Hi, have you solved this issue? – Junior Jiang Apr 22 '19 at 07:26
  • @JuniorJiang-MSFT I did solve it. I ended up rewriting the whole process. This code here was written following a tutorial. I looked through the xamarin docs to get a better understanding of all this stuff and rewrote a simpler version that actually works for me. – CaptainKirk Apr 24 '19 at 03:01
  • @KirkK Great ! Remember to share the answer here and mark it :) – Junior Jiang Apr 24 '19 at 03:07

0 Answers0