winform使用webservice写cookie出错的问题
webservice大致代码如下:[WebMethod(EnableSession=true)]
public void ControlCookie()
{
HttpCookie cookie = new HttpCookie("MyCooKies");
cookie["cUser"] = "UserName";
cookie.Expires = DateTime.Parse("2020-02-02");
HttpContext.Current.Response.Cookies.Add(cookie);
}
使用winform引用:
ServiceReference3.WebService1SoapClient ws = new ServiceReference3.WebService1SoapClient();
ws.ControlCookie();
发现cookie根本没有写入,而使用webfrom调用webservice则没有问题,请教这是为啥? --------------------编程问答-------------------- 没人理我呀 我顶一下 --------------------编程问答-------------------- 检查客户端配置文件 app.config 中的 allowCookies 是否设为true了(默认是false)
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap" ... allowCookies="true" --------------------编程问答--------------------
按照这个做了配置 还是不管用阿 --------------------编程问答-------------------- 客户端是不会生成cookie"文件",你只能在客户端应用周期内保持Session。
(它实际是保存在客户端代理类里的CookieContainer里,这个在.net 2.0生成的Proxy里有这个属性,3.5之后没有了。取代为allowCookie配置)
服务端session应该是好用的。
比如你现在在另一个方法里通过Session取UserName是可以取到的。
你说的不管用是什么? --------------------编程问答-------------------- 服务器上的webservice里面有一个写cookie的方法,我想用客户端winform去调用,在客户端保存cookie --------------------编程问答-------------------- 按说客户端里应该能接收到来至服务端的自定义cookie,但我还没有试验过。
你可以这么用,当启用allowCookie后,服务端能通过sessionId来识别客户端,并返回对应的Session数据。
[WebMethod(EnableSession=true)]
public void Logon(string username)
{
HttpContext.Current.Session["UserName"] = username;
}
[WebMethod(EnableSession=true)]
public string GetUserName()
{
return HttpContext.Current.Session["UserName"] as string;
} --------------------编程问答-------------------- 恩 但是客户端要做的只是调用webservice方法写cookie,客户端不需要知道具体cookie的值 --------------------编程问答-------------------- 继续求答案 --------------------编程问答-------------------- 我测试没问题啊。你说的不能用是啥意思?
[WebMethod(EnableSession=true)]
public void Login(string username)
{
HttpCookie cookie = new HttpCookie("MyCooKies");
cookie["user"] = username;
cookie.Expires = DateTime.Parse("2020-02-02");
HttpContext.Current.Response.Cookies.Add(cookie);
}
[WebMethod(EnableSession = true)]
public string GetUserName()
{
var username = HttpContext.Current.Request.Cookies["MyCooKies"].Values["user"];
return username;
}
--------------------编程问答-------------------- 补充:这个cookie周期和客户端程序运行周期一样。程序关闭,cookie就over了。
如果你想在客户端持久化,需要用.net2.0生成客户端代理,
那样你可以直接使用代理的CookieContainer然后把它序列化在客户端,
下次程序运行再反序列化回来。
形如:
// 客户端启动时调用反序列化,取得cookie
if (File.Exists("MyCookie.dat"))
{
using (var fs = File.OpenRead("MyCookie.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
cookie = (CookieContainer)bf.Deserialize(fs);
}
}
else
{
cookie = new CookieContainer();
}
// 第一次Logon
using (var svc = new WebSvc2.Service1())
{
svc.CookieContainer = cookie;
svc.Login(textBox1.Text);
using (var fs = File.OpenWrite("MyCookie.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, cookie);
}
}
// 其他调用
using (var svc = new WebSvc2.Service1())
{
svc.CookieContainer = cookie;
MessageBox.Show(svc.GetUserName());
}
--------------------编程问答--------------------
补充:.NET技术 , Web Services