Xamarin Forms working with cookies

MdNaushadMdNaushad INMember ✭✭✭

Hi All,
I have seen a number of posts of working with cookies in Xamarin Forms, most of them use the webview for login against a server which then responds back with Success Response and cookies. I assume these cookies are automatically send back in each subsequent request(correct me If my assumption is wrong here).
However I want to know what happens when webview is not used and we have an xaml Login page instead.
Considering a scenario where I post a HttpClient request to server and get back the response along with the authentication cookies.
Please help me in clearing the following doubts/questions:
1) As per my observation, If I am using the same HttpClient object(which I used for login) to call the REST Api in the following way

            var handler = new HttpClientHandler()
            {
                AllowAutoRedirect = false,
                UseCookies = true,
            };
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            Uri uri = new Uri("https://xyz.com/getData");
            var response = await client.GetAsync(uri);
            var data = await response.Content.ReadAsStringAsync();

the cookies are send with the HttpClient request and I get the success response. This restricts me to use the same HttpClient object on each and every subsequent REST Api request.

2) I read in few posts that you can save the Cookie Container in your custom renderer and pass the same in HttpClient request.
3) Another way is to use the read the cookies that you need from the Cookie Container, save them in https://github.com/jamesmontemagno/SettingsPlugin of @JamesMontemagno and when you need to access the Rest Api, reassemble the cookie container and send it across.

Which would be the ideal way of working with cookies out of 3 approaches I have found so far? Also, at any place If my understanding is not clear, please feel free to correct me.

Best Answers

  • MdNaushadMdNaushad IN ✭✭✭
    Accepted Answer

    @NMackay said:
    @MdNaushad

    I can't post the whole class but basically it's a static class that handles, get, post etc and you can pass generic types.

        public static class RestServiceCall<T>
        {
            private static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore
            };
    
            private static HttpClient Client = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) };
    
            public static async Task<List<T>> PostFetchList(string url, object toPost, CancellationToken ct,
                                              Dictionary<string, string> headers = null, Dictionary<string, string> token = null)
    

    @NMackay Thank you for posting the code, that has got me going.

Answers

  • NMackayNMackay GBInsider, University mod

    I would say no 3 would be your best approach.

  • NMackayNMackay GBInsider, University mod

    I abstract persisting the session key etc into a security service i inject into my base view model, it stores the values in a similar approach to the settings pluggin, I have a static class that handles the HTTP requests, I don't persist the httpclient as such as it has unwanted side effects so option 1 could cause you issues.

    https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

  • MdNaushadMdNaushad INMember ✭✭✭

    @NMackay - Thank you. As of now I am planning to go ahead with approach 3.

  • MdNaushadMdNaushad INMember ✭✭✭
    edited September 2017

    @NMackay said:
    I abstract persisting the session key etc into a security service i inject into my base view model, it stores the values in a similar approach to the settings pluggin, I have a static class that handles the HTTP requests, I don't persist the httpclient as such as it has unwanted side effects so option 1 could cause you issues.

    https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

    Thank you so much for sharing the link.
    Actually I am also using currently a single instance of HttpClient using the Singleton pattern(i.e. restricting any new creation of HttpClient). In my approach I am using a BaseContext class which has the HttpClient created.

    Also, from creating an Http Client to calling post and get methods are you handling them in your static class?

  • MdNaushadMdNaushad INMember ✭✭✭
    Accepted Answer

    @NMackay said:
    @MdNaushad

    I can't post the whole class but basically it's a static class that handles, get, post etc and you can pass generic types.

        public static class RestServiceCall<T>
        {
            private static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore
            };
    
            private static HttpClient Client = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) };
    
            public static async Task<List<T>> PostFetchList(string url, object toPost, CancellationToken ct,
                                              Dictionary<string, string> headers = null, Dictionary<string, string> token = null)
    

    @NMackay Thank you for posting the code, that has got me going.

Sign In or Register to comment.