2.9Setting Cookie (Simulated/Automatic Login)

Created on Aug 17, 2026~5 min read

A Cookie is a piece of data sent by the server in an HTTP response. The client (optionally) stores the Cookie and returns it in subsequent requests. This allows the client and server to share state. When sending an HTTP remote request, there are two ways to set Cookie.

  • Set Cookie globally via HttpClient

This approach allows sharing Cookie under the same-origin domain, and if the server returns new Cookie, these Cookie will be automatically carried in subsequent requests, which is very suitable for implementing features such as automatic website login.

cs
var cookieContainer = new CookieContainer();// Optionally set the default CookiecookieContainer.Add(new Uri("https://furion.net"), new Cookie("cookieName", "cookieValue"));// Default client configurationservices.AddHttpClient(string.Empty)    .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler    {        CookieContainer = cookieContainer,        UseCookies = true,   // Automatically handle Cookies, will be carried automatically in subsequent requests        AllowAutoRedirect = true    });
  • Set Cookie for a single request

This approach only takes effect for the current request; if the server returns new Cookie, they will not be carried by subsequent requests.

cs
await httpRemoteService.SendAsync(HttpRequestBuilder.Get("http://furion.net")    .WithCookie("cookieName", "cookieValue")    // Set a single Cookie    .WithCookies(new { name = "furion", author = "monksoul" }));    // Set multiple Cookies

Note: In practical applications, you may need to choose the appropriate Cookie setting approach based on your specific requirements and ensure the security of Cookie, for example avoiding cross-site scripting attacks (XSS) and cross-site request forgery attacks (CSRF). At the same time, for sensitive information, it is recommended to use more secure authentication mechanisms such as OAuth, JWT, etc.