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.

有帮助吗?

解决方案 2

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));
 }

其他提示

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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top