How to send or post cookie from client to server in .net

52 Views Asked by At

I have implemented this code to request a page and read the cookies set by the server:

myURI = new Uri(strURI);
request = (HttpWebRequest)HttpWebRequest.Create(myURI);
request.CookieContainer = new CookieContainer();
request.CookieContainer.GetCookies(myURI);

using (var response = (HttpWebResponse)request.GetResponse())
{
    foreach (Cookie cook in response.Cookies)
    {
        Console.WriteLine("  Cookie:");
        Console.WriteLine($"{cook.Name} = {cook.Value}");
        Console.WriteLine($"Domain: {cook.Domain}");
        Console.WriteLine($"Path: {cook.Path}");
        Console.WriteLine($"Port: {cook.Port}");
        Console.WriteLine($"Secure: {cook.Secure}");
        Console.WriteLine($"When issued: {cook.TimeStamp}");
    }
}

Is there a way to create new cookies and send it to the browser cookies, so that the server can read them?

1

There are 1 best solutions below

0
Shervin Ivari On

You can use HttpClientHandler with CookieContainer to send requests with cookies.

For Post your request with cookies

var cookieContainer = new CookieContainer();

using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = new Uri(BaseAddress + route) })
{
                                    
 cookieContainer.Add(client.BaseAddress, new Cookie(".AspNetCore.Identity.Application", "somevalue"));
 cookieContainer.Add(client.BaseAddress, new Cookie("Cookie1", "somevalue"));

  var message = new HttpRequestMessage(httpMethod, client.BaseAddress)
  {
      //If you have json body
      Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")
  };

  var result = client.SendAsync(message).Result;

  result.EnsureSuccessStatusCode();
  }

And for reading cookies if you only have access to HttpResponseMessage You can read it from headers

 var headers = new Dictionary<string, string>();

    foreach (var item in result.Headers.GetValues("Set-Cookie"))
    {
        int startpoint = item.IndexOf("=") + 1;
        var headername = item.Substring(0, startpoint);

        if (headers.ContainsKey(headername)
            && string.IsNullOrEmpty(headers[headername]))
            headers.Remove(headername);

        headers.Add(headername
            , item.Substring(startpoint, item.IndexOf(";") - startpoint));
    }
    var token = headers[".AspNetCore.Identity.Application="];//cookie value by name