如何在cookie Aware Client中使用auth cookie访问安全网页?

时间:2014-01-27 09:51:10

标签: asp.net wcf cookies

最初我登录到一个安全的网页,然后手动获取cookie,然后我必须设置cookie,同时再次调用从授权的网址获取数据。 我怎样才能使一个cookie感知客户端不需要一次又一次地设置auth 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());

1 个答案:

答案 0 :(得分:2)

您可以像这样创建一个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);
                }