How to Get/Set Cookies in Windows.Web.Http API

Elvis Xia 131 Reputation points Microsoft Employee
2019-10-30T07:22:26.693+00:00

I have used the Windows.Web.Http API in my app to implemenet a website Login function.

The current situation is that I want to sign in a website and the website has a special parameter in the login post data which can be found in the login page. I found I have to save the cookie when I do the previous request. If not, it will make another random token.
I have checked those class: HttpRequestMessage, HttpResponseMessage, HttpClient, but I find nothing about the Cookies.
At last I find a class called HttpBaseProtocolFilter and it has a member called CookieManager. But I don't know what to do with it.

So I hope the answers can contain some general codes for how to get/set cookies in Windows.Web.Http API correctly.

Universal Windows Platform (UWP)
0 comments No comments
{count} vote

Accepted answer
  1. Roy Li - MSFT 32,721 Reputation points Microsoft Vendor
    2019-10-30T08:17:30.607+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    To add or delete an HttpCookie or view the cookies associated with an app, we can refer to the HttpCookieManager.
    For how to using it, you can refer the following code:

    //To get/set cookies  
    using (var protocolFilter = new HttpBaseProtocolFilter())  
                {  
                    //get CookieManager instance  
                    var cookieManager = protocolFilter.CookieManager;  
                    //get cookies  
                    var cookies = cookieManager.GetCookies(uri);  
                    foreach (var cookie in cookies)  
                    {  
                        Debug.Write(cookie.Value);  
                    }  
                    //you can also SetCookie  
                    //cookieManager.SetCookie(MyCookie);  
                }  
      
      
    

    Meanwhile, you can also define the cookie usage behavior that is used in the CookieUsageBehavior property.

                    var protocolFilter = new HttpBaseProtocolFilter()  
                    //Do not handle cookies automatically. you can set it as your requirements.  
                    protocolFilter.CookieUsageBehavior = HttpCookieUsageBehavior.NoCookies;  
                    // Create a HttpClient  
                    var httpClient = new HttpClient(protocolFilter);  
    
     
    

    Thanks.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful