Asp.net 如何在cookie感知客户端中使用auth cookie访问安全网页?

Asp.net 如何在cookie感知客户端中使用auth cookie访问安全网页?,asp.net,wcf,cookies,Asp.net,Wcf,Cookies,最初我登录到一个安全的网页,然后手动获取cookie,然后我必须设置cookie,同时进行另一个调用以从授权的web url获取数据。 如何使一个cookie感知的客户端不需要反复设置身份验证cookie。它应该自动设置auth cookie并获取所需的数据 我的代码是 CPSession retVal = null; if (guid != "") retVal = TokenManager.getSessionInfo(guid);

最初我登录到一个安全的网页,然后手动获取cookie,然后我必须设置cookie,同时进行另一个调用以从授权的web url获取数据。 如何使一个cookie感知的客户端不需要反复设置身份验证cookie。它应该自动设置auth cookie并获取所需的数据

我的代码是

CPSession retVal = null;
        if (guid != "")
            retVal = TokenManager.getSessionInfo(guid);

        ServicePointManager.ServerCertificateValidationCallback = delegate
        { return true; };

        HttpWebRequest httpWReq =
        (HttpWebRequest)WebRequest.Create(address);
        httpWReq.CookieContainer = new CookieContainer();

        Encoding encoding = new UTF8Encoding();
        byte[] bdata = encoding.GetBytes(postData);

        httpWReq.ProtocolVersion = HttpVersion.Version11;
        httpWReq.Method = "PUT";
        httpWReq.ContentType = "application/json; charset=utf-8";
        httpWReq.CookieContainer.SetCookies(new Uri(address), retVal.getAttributeValue(CookieType));  // here I'm setting cookie manually.

        httpWReq.ContentLength = bdata.Length;

        Stream stream = httpWReq.GetRequestStream();
        stream.Write(bdata, 0, bdata.Length);
        stream.Close();

        HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
        string s = response.ToString();
        StreamReader reader = new StreamReader(response.GetResponseStream());

您可以像这样创建一个cookie感知客户端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace SunPowerService.Service
{
public class CookieAwareWebClient : WebClient
{
    public 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;
    }
}
}
你可以这样称呼它

using (var client = new CookieAwareWebClient())
                {
                    Uri uri = new Uri("YourUrlToGetAuthCookie");
                    client.m_container.SetCookies(uri, strCookieVal);
                    jsonresponse = client.DownloadString(uri);
                }