简体   繁体   English

如何将Cookie容器与RestSharp和ASP.NET会话一起使用?

[英]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. 但是,由于将RestSharp用作独立客户端,因此我不确定如何将请求保留在会话中。 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? 如何确保RestSharp中的RestClient发送所有将来的请求,并正确设置cookie,以便在服务调用内部可以正确检索会话变量?

I've been looking at the cookie container with HttpFactory but there doesn't seem to be any documentation on this anywhere. 我一直在用HttpFactory查看cookie容器,但似乎在任何地方都没有任何文档。

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. 如果有人遇到类似的问题,请注意,对于简单的“在每次请求后存储我的cookie”问题,并不需要上述条件。 Jaffas approach above works, but you can simply attach a CookieStore to your RestClient and have the cookies be stored automatically . 上面的Jaffas方法可行,但是您可以简单地将CookieStore附加到RestClient并自动存储cookie。 I know this is not a solution for everyone, since you might want to store dedicated cookies only. 我知道这不是每个人都可以解决的方法,因为您可能只想存储专用的 cookie。 On the other hand it makes your life easier for testing a REST client! 另一方面,它使您测试REST客户端的工作变得更加轻松! (I used Jaffas variables for ease): (为方便起见,我使用了Jaffas变量):

        CookieContainer _cookieJar = new CookieContainer();
        var client = new RestClient("http://<test-server>/letteron"); //test URL
        client.CookieContainer = _cookieJar;

I worked this out in the end. 我最终解决了这个问题。 Basically create a cookie container, then add the session cookie from the response into the cookie container. 基本上创建一个cookie容器,然后将响应中的会话cookie添加到cookie容器中。 All future requests will then contain this cookie. 然后,所有将来的请求都将包含此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));
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM