question

elvisxia avatar image
elvisxia asked ·

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

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.

windows-uwp
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RoyLi-MSFT avatar image
RoyLi-MSFT answered ·

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 comment Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks. This helped a lot.

0 Votes 0 · ·