C# 如何在 RestSharp 和 ASP.NET 会话中使用 cookie 容器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8823349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use the cookie container with RestSharp and ASP.NET sessions?
提问by jaffa
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.
但是,我不确定如何将请求保留在会话中,因为我使用 RestSharp 作为分离的客户端。我需要以某种方式在成功授权后从服务器取回密钥,然后在以后的每次调用中,使用存储在会话中的密钥检查密钥。
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 容器,但似乎在任何地方都没有关于此的任何文档。
采纳答案by jaffa
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.
我最终解决了这个问题。基本上创建一个 cookie 容器,然后将响应中的会话 cookie 添加到 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));
}
回答by Peter Branforn
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 dedicatedcookies only. On the other hand it makes your life easier for testing a REST client! (I used Jaffas variables for ease):
如果有人遇到类似的问题,请注意,对于简单的“每次请求后存储我的 cookie”问题,上述内容并不是必需的。上面的 Jaffas 方法有效,但您可以简单地将 CookieStore 附加到您的 RestClient 并自动存储 cookie 。我知道这不是适合所有人的解决方案,因为您可能只想存储专用cookie。另一方面,它可以让您更轻松地测试 REST 客户端!(为了方便,我使用了 Jaffas 变量):
CookieContainer _cookieJar = new CookieContainer();
var client = new RestClient("http://<test-server>/letteron"); //test URL
client.CookieContainer = _cookieJar;

