如何保持会话两个电话之间活在C#应用程序的Web服务? [英] How to keep session alive between two calls to a web service in a c# application?

查看:104
本文介绍了如何保持会话两个电话之间活在C#应用程序的Web服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是很容易理解。结果
我打电话从C#应用程序的Web服务(的.asmx,与会话启用)。

This is quite straight forward.
I'm calling a web-service (.asmx, with session enabled) from a c# application.

我希望每个调用与为previous一个相同的会话密钥(而不是每次都创建一个新的会话密钥)。

I want each call to be with the same session key as the previous one (as opposed to creating a new session key each time).

下面是我的(没有-出的最普通)code:

Here's my (nothing-out-of-the-ordinary) code:

public string invokeMethod(string methodUrl)
{
 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(methodUrl);
 req.Method = "GET";
 req.ContentLength = 0;
 var result = new StringBuilder();
 using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
 {
   StreamReader sr = new StreamReader(res.GetResponseStream());
   result.Append(sr.ReadToEnd());
 }
 return result.ToString();
}  

现在我想再次调用它,在同一个会话。

Now I want to call it again, in the same session.

补充:感谢瓦利德的答案,我想我应该做这样的事情(检索会话ID后):结果
添加一次:这是它是如何做的:

Added: Thanks to Waleed's answer, I think I should be doing (after retrieving the session id) something like:
Added once more: This is how it's done:

if (!string.IsNullOrEmpty(currentSessionID))
{
  Cookie cookie = new Cookie("ASP.NET_SessionId", currentSessionID);
  cookie.Domain=myDomain;  //Will not work without this line!
  req.CookieContainer.Add(cookie);  
}

再次感谢。

推荐答案

如果我理解正确的问题,我相信你会需要从响应会话cookie(你第一次调用Web服务),并添加它在随后的呼叫的请求。

If I understand the question correctly, I believe you'll need to get the session cookie from the response (the first time you call the web service) and add it to the request in the subsequent calls.

编辑:

使用的CookieContainer是正确的做法,但要知道,这是的默认空,所以你必须向提出请求之前分配的CookieContainer对象的属性(请参阅MSDN的文章中的例子code)。

Using CookieContainer is the correct way but be aware that it's null by default so you'll have to to assign a CookieContainer object to the property before making the request (see the example code in the MSDN's article).

至于cookie的名称,ASP.NET会话cookie的默认名称为ASP.NET_SessionId,但名称可以是不同的,因为它可以在web.config中被改变,或者他们可能不使用ASP.NET会话(自己的实现为例),所以你必须检查你的应用程序域获取饼干(你可以,如果你使用Firefox或Chrome使用HTTP嗅探器一样提琴手,或更容易,你可以检查名字和你在选项对话框,域)得到的cookie内容。

As to the cookie name, the default name for ASP.NET session cookie is ASP.NET_SessionId, but the name can be different as it can be changed in web.config, or they might not be using ASP.NET sessions (their own implementation for example), so you'll have to check the cookies you get from the domain of that application (You can use an HTTP sniffer like Fiddler, or more easily if you're using FireFox or Chrome, you can check the names and contents of the cookies you get from that domain in the options dialog box).

这篇关于如何保持会话两个电话之间活在C#应用程序的Web服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆