5

I want to make a POST request to HTTP server, but I need to "include" a cookie in the request, I have the cookie but I dont know how to mess with cookie container

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Host = "url.com";
request.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11";
request.Referer = "http://url.com";
request.Headers.Add("X-Requested-With", "XMLHttpRequest");
request.Headers.Add("X-Prototype-Version", "1.7");
request.Headers.Add("Accept-Encoding: gzip, deflate");

and this is a sample cookie:

Cookie recentlyVisitedAppHubs=233450%2C231430%2C48110%2C45760; Language=spanish; strInventoryLastContext=440_2; __utma=268881843.118202637.1372069740.1373472452.1373473085.10; __utmb=268881843.21.10.1373473085; __utmz=268881843.1373473085.10.4.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); rgTopicView_General_4312225=%7B%22828934913396342649%22%3A%221373450285%22%2C%22846939615003500718%22%3A1373473557%7D; timezoneOffset=7200,0; sessionid=NDExNjE1NDE5; Login=765611979917322708A9C768; steamRememberLogin=76561197991732272; __utma=268881843.118202637.1372069740.1373472452.1373473085.10; __utmb=268881843.22.10.1373473085; __utmc=268881843; __utmz=268881843.1373473085.10.4.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)

But I dont know how to convert that cookie into a Cookie container and then add it to the request. request.CookieContainer = cookie;

Gonzalo Hernandez
  • 727
  • 2
  • 9
  • 25

3 Answers3

6
String CookieStr = "recentlyVisitedAppHubs=233450%2C231430%2C48110%2C45760; 
Language=spanish; strInventoryLastContext=440_2";
CookieContainer cookiecontainer = new CookieContainer();
string[] cookies = CookieStr.Split(';');
foreach (string cookie in cookies)
   cookiecontainer.SetCookies(new Uri("http://url.com"), cookie);
request.CookieContainer = cookiecontainer;
artoor32
  • 61
  • 1
  • 2
  • 1
    Welcome to Stack Overflow! Please write an explanation about what your code does and how it is different so others can understand! – Aᴄʜᴇʀᴏɴғᴀɪʟ Sep 24 '16 at 01:17
  • 1
    create cookie from string – artoor32 Sep 29 '16 at 01:46
  • 1
    This answer is concise and answers the Title of the Question while the accepted one does not address the full task of parsing a cookie string into a CookieContainer. Wanted to leave a comment as I value this answer. – ttugates Mar 11 '22 at 19:02
5
//build uri and cookie
Uri uri = new Uri("domain");
Cookie cookie = new Cookie("name", "value");

//build request
HttpWebRequest request = WebRequest.Create("domain") as HttpWebRequest;
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(uri, cookie);

Resources:

Community
  • 1
  • 1
KC-Flip
  • 139
  • 3
  • 10
1

Sorry for the "hurry" code but this is my way to parse a string to cookie options, key, value.

public class CookieWithOptions
{
    CookieOptions options { get; set; } = new CookieOptions();
    string Key { get; set; } = default!;
    string Value { get; set; } = default!;
}

public static class CookieProperties
{
    public const string Expires = "expires";
    public const string Expired = "expired";
    public const string Path = "path";
    public const string Domain = "domain";
    public const string Secure = "secure";
    public const string SameSite = "sameSite";
    public const string HttpOnly = "httpOnly";
    public const string MaxAge = "maxAge";
    public const string IsEssential = "isEssential";
}

Get the CookieWithOptions from ExtractCookie method:

var cookie = ExtractCookie(cookieString);

ExtractCookie Implementation:

private CookieWithOptions ExtractCookie(string cookieString)
{
    CookieWithOptions cookie = new();
    
    var parts = cookieString!.Split("; ");
    var claims = new Dictionary<string, string>();

    foreach (var part in parts)
    {
        var keyValuePair = part.Split('=');
        claims.Add(keyValuePair.First(), keyValuePair.Last());
    }

    SetCookieOptions(claims, cookie);

    return cookie;
}

SetCookieOptions:

public void SetCookieOptions(
    Dictionary<string, string> claims,
    CookieWithOptions cookie)
{
    foreach (var claim in claims)
    {
        switch (claim.Key)
        {
            case CookieProperties.Expires:
                cookie.Options.Expires = DateTime.ParseExact(
                    claim.Value,
                    "ddd, d MMM yyyy HH:mm:ss GMT",
                    CultureInfo.GetCultureInfoByIetfLanguageTag("en-us"),
                    DateTimeStyles.AdjustToUniversal);
                break;
            case CookieProperties.Secure:
                cookie.Options.Secure = bool.Parse(claim.Value);
                break;
            case CookieProperties.IsEssential:
                cookie.Options.IsEssential = bool.Parse(claim.Value);
                break;
            case CookieProperties.SameSite:
                cookie.Options.SameSite = Enum.Parse<SameSiteMode>(claim.Value);
                break;
            case CookieProperties.Path:
                cookie.Options.Path = claim.Value;
                break;
            case CookieProperties.Domain:
                cookie.Options.MaxAge = TimeSpan.Parse(claim.Value);
                break;
            case CookieProperties.HttpOnly:
                cookie.Options.HttpOnly = bool.Parse(claim.Value);
                break;
            default:
                cookie.Key = claim.Key;
                cookie.Value = claim.Value;
                break;
        }
    }
}

also make sure that the two words options in CookieProperties e.g. isEssential are formated the right way because i'm not sure if it should stay camelCase :)

SY7K ْ
  • 11
  • 2