c# - ashx 请求中的 Session.SessionId 持久化

标签 c# asp.net web-services ashx

当我对服务进行 webrequest 调用时,为什么它总是生成一个新的 sessionid?

这就是我从 sitea.com 调用的方式

WebClient fs = new WebClient();
            var data = fs.DownloadData("http://siteb.com/serice.ashx");
            var tostring = System.Text.Encoding.ASCII.GetString(data);
            return tostring;

这是 siteb.com 上的服务代码

[WebMethod(EnableSession = true)]
    private string Read(HttpContext context)
    {
        var value = context.Session.SessionId;
        if (value !=null) return value.ToString();
            return "false";
    }

每个请求的值总是不同的。我怎样才能坚持下去?

最佳答案

您必须接收 session ID 并将其传递给后续请求。默认情况下,它将在 cookie 中发送,但 WebClient 不处理 cookie。您可以使用 CookieAwareWebClient解决这个问题:

public class CookieAwareWebClient : WebClient
{
    private CookieContainer m_container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = m_container;
        }
        return request;
    }
}

只要您重复使用相同的 Web 客户端实例,您就应该获得相同的 session ID(当然前提是 session 不会超时)。

关于c# - ashx 请求中的 Session.SessionId 持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11476748/

相关文章:

c# - 使用图形 API 查询 Azure AD

c# - Angular Web 应用程序数据绑定(bind)不起作用

c# - Array Slice 创建新数组

asp.net - ApplicationClass Documents.Open 为 64 位系统上的 ASP.NET 站点返回 null

c# - 如何编写自定义模板字段类 DataControlField

web-services - OTRS Webservice 作为请求者测试

c# - 如何在 C# 中模拟友谊?

asp.net - IIS 工作进程使用大量内存?

web-services - Karate 自动设置 Content-Type header

java - 可选 nillable 值的 JAX-WS 处理