Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the cookie container with RestSharp and ASP.NET sessions?

I'd like to be able to call an authentication action on a controller and if it succeeds, store the authenticated user details in the session.

However, I'm not sure how to keep the requests inside the session as I'm using RestSharp as a detached client. I need to somehow get a key back from the server on successful authorisation and then for each future call, check the key with that stored in the session.

How do I ensure the RestClient in RestSharp sends all future requests with the cookie set correctly so inside service calls, the session variable can be retrieved correctly?

I've been looking at the cookie container with HttpFactory but there doesn't seem to be any documentation on this anywhere.

like image 946
jaffa Avatar asked Jan 11 '12 16:01

jaffa


2 Answers

If someone is having a similar problem, please note that the above is not quite required for a simple "store my cookies after each request" problem. Jaffas approach above works, but you can simply attach a CookieStore to your RestClient and have the cookies be stored automatically. I know this is not a solution for everyone, since you might want to store dedicated cookies only. On the other hand it makes your life easier for testing a REST client! (I used Jaffas variables for ease):

        CookieContainer _cookieJar = new CookieContainer();
        var client = new RestClient("http://<test-server>/letteron"); //test URL
        client.CookieContainer = _cookieJar;
like image 82
Peter Branforn Avatar answered Nov 02 '22 18:11

Peter Branforn


I worked this out in the end. Basically create a cookie container, then add the session cookie from the response into the cookie container. All future requests will then contain this cookie.

 var sessionCookie = response.Cookies.SingleOrDefault(x => x.Name == "ASP.NET_SessionId");
 if (sessionCookie != null)
 {
    _cookieJar.Add(new Cookie(sessionCookie.Name, sessionCookie.Value, sessionCookie.Path, sessionCookie.Domain));
 }
like image 13
jaffa Avatar answered Nov 02 '22 18:11

jaffa