当客户端是Windows应用程序C#时,webservice如何维护会话?

时间:2014-07-11 07:44:13

标签: c# web-services

我的网络服务中的方法C#

[WebMethod(EnableSession=true)]
public string HelloWorld()
{
    int? Count = (int?)Session["Count"];
    if(Count == null) 
    {
        Count = 0;
    }

    Count++;

    Session["Count"] = Count;

   return "Hello World - Call Number : " + Count.ToString();
}

我的窗口应用程序客户端:

using WindowsFormsApplicationName.ServiceReference;
// ...
private NameServiceSoapClient WS = new NameServiceDataSoapClient();
//...

private void btnTest_Click(object sender, EventArgs e)
{
    // Can you write me how to use CookieContainer here ?
    string DataPOST = WS.HelloWorld();
    MessageBox.Show(DataPOST);
}

如果我不使用HttpWebrequest,你能否告诉我如何在这里使用CookieContainer?

非常感谢:)

2 个答案:

答案 0 :(得分:1)

是的,从Windows应用程序调用WebMethod时需要使用CookieContainer。

HttpWebRequest对象具有您需要设置的CookieContanier属性。只需创建一个CookieContainer对象(每个会话只有一次)并将其分配给共享同一会话的所有请求。

CookieContainer here的官方文档中有一个示例。请记住为您的所有请求使用相同的CookieContainer。

答案 1 :(得分:0)

对于网络服务参考,您有一个CookieContainer属性,就像在HttpWebRequest中一样。

对于服务参考(是的,很棒的命名......),您只需在app.config中的服务绑定中使用cookie:

<system.ServiceModel>
    <bindings>
        <basicHttpBinding allowCookies="true">
    </bindings>
</system.ServiceModel>

这是因为服务引用不一定与HTTP绑定,而cookie是HTTP功能。

如果你需要在运行时处理这个问题,可以使用OperationContext,但对于大多数情况来说,这是非常糟糕的,而且实在是太过分了。

相关问题