1

My question is how can I do POST request, next get cookie from that request and set it to the next request for example GET type in C#? Please for example code.

I had tried a lot of times, for example by CookieAwareWebClient method but it not working:

public class CookieAwareWebClient : WebClient
{
    public CookieContainer CookieContainer { get; set; }

    public CookieAwareWebClient()
        : base()
    {
        CookieContainer = new CookieContainer();
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);

        HttpWebRequest webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = CookieContainer;
        }

        return request;
    }
}

What I need? I need to login by POST requests and next do for example 10-20 request POST/GET by the authenticate cookie from first request (login)

I'm doing it by this:

//Create an instance of your new CookieAware Web Client
using (var client = new CookieAwareWebClient())
{
    //Authenticate (username and password can be either hard-coded or pulled from a settings area)
    var values = new NameValueCollection{{ "UserName", username },{ "Password", password }};

     client.UploadValues(new Uri("http://www.yourdomain.com/Account/LogOn/"), "POST", values);

     client.UploadString(new Uri("http://www.yourdomain.com/Secure/YourSecureMethod"), 
 "POST", "Example Message");           
}

But I cant set this cookie to my next requests (next reauest creating thier own NEW non-authenticated cookies)

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Narkon
  • 398
  • 2
  • 17
  • "tried a lot" does not give any chance to help you with your problem. Sample showing 2 request with reading/writing headers should be small and significantly improve your post... And depending on what you actually trying to do it may be even answered before... – Alexei Levenkov Sep 27 '14 at 19:07
  • Thanks for sample... but you need to show usage too with sample urls (sample domain portion is likely enough as long it shows which domains are same and which are different) for someone to see why it fails. – Alexei Levenkov Sep 27 '14 at 19:10
  • Have you looked at http://stackoverflow.com/questions/1777221/using-cookiecontainer-with-webclient-class ? – Simon Smeets Sep 27 '14 at 20:31
  • 1
    I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Sep 27 '14 at 21:25

0 Answers0