Read and Write Cookies in Asp.net C#
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
HTTP Cookies in ASP.NET Web API
by Mike Wasson
This topic describes how to send and receive HTTP cookies in Web API.
Background on HTTP Cookies
This section gives a brief overview of how cookies are implemented at the HTTP level. For details, consult RFC 6265.
A cookie is a piece of data that a server sends in the HTTP response. The customer (optionally) stores the cookie and returns it on subsequent requests. This allows the client and server to share state. To set a cookie, the server includes a Set up-Cookie header in the response. The format of a cookie is a name-value pair, with optional attributes. For instance:
Set-Cookie: session-id=1234567
Hither is an example with attributes:
Set-Cookie: session-id=1234567; max-age=86400; domain=example.com; path=/;
To return a cookie to the server, the client includes a Cookie header in subsequently requests.
Cookie: session-id=1234567
An HTTP response tin can include multiple Set-Cookie headers.
Set-Cookie: session-token=abcdef; Set-Cookie: session-id=1234567;
The client returns multiple cookies using a single Cookie header.
Cookie: session-id=1234567; session-token=abcdef;
The telescopic and duration of a cookie are controlled by following attributes in the Ready-Cookie header:
- Domain: Tells the client which domain should receive the cookie. For example, if the domain is "example.com", the client returns the cookie to every subdomain of example.com. If not specified, the domain is the origin server.
- Path: Restricts the cookie to the specified path within the domain. If not specified, the path of the asking URI is used.
- Expires: Sets an expiration date for the cookie. The client deletes the cookie when information technology expires.
- Max-Age: Sets the maximum age for the cookie. The client deletes the cookie when it reaches the maximum historic period.
If both Expires
and Max-Historic period
are set, Max-Historic period
takes precedence. If neither is gear up, the client deletes the cookie when the current session ends. (The verbal meaning of "session" is determined by the user-amanuensis.)
Even so, be aware that clients may ignore cookies. For example, a user might disable cookies for privacy reasons. Clients may delete cookies before they expire, or limit the number of cookies stored. For privacy reasons, clients often pass up "third party" cookies, where the domain does non match the origin server. In short, the server should not rely on getting dorsum the cookies that it sets.
Cookies in Web API
To add together a cookie to an HTTP response, create a CookieHeaderValue instance that represents the cookie. So telephone call the AddCookies extension method, which is defined in the Arrangement.Cyberspace.Http. HttpResponseHeadersExtensions grade, to add the cookie.
For example, the following code adds a cookie within a controller action:
public HttpResponseMessage Become() { var resp = new HttpResponseMessage(); var cookie = new CookieHeaderValue("session-id", "12345"); cookie.Expires = DateTimeOffset.Now.AddDays(1); cookie.Domain = Asking.RequestUri.Host; cookie.Path = "/"; resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); render resp; }
Notice that AddCookies takes an array of CookieHeaderValue instances.
To extract the cookies from a client request, call the GetCookies method:
string sessionId = ""; CookieHeaderValue cookie = Request.Headers.GetCookies("session-id").FirstOrDefault(); if (cookie != null) { sessionId = cookie["session-id"].Value; }
A CookieHeaderValue contains a drove of CookieState instances. Each CookieState represents i cookie. Use the indexer method to go a CookieState past name, as shown.
Structured Cookie Data
Many browsers limit how many cookies they will store—both the total number, and the number per domain. Therefore, it can exist useful to put structured data into a single cookie, instead of setting multiple cookies.
Note
RFC 6265 does not define the construction of cookie data.
Using the CookieHeaderValue class, you can pass a listing of name-value pairs for the cookie information. These name-value pairs are encoded as URL-encoded form data in the Set-Cookie header:
var resp = new HttpResponseMessage(); var nv = new NameValueCollection(); nv["sid"] = "12345"; nv["token"] = "abcdef"; nv["theme"] = "dark blueish"; var cookie = new CookieHeaderValue("session", nv); resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
The previous code produces the following Set-Cookie header:
Ready-Cookie: session=sid=12345&token=abcdef&theme=dark+blueish;
The CookieState class provides an indexer method to read the sub-values from a cookie in the request message:
string sessionId = ""; cord sessionToken = ""; string theme = ""; CookieHeaderValue cookie = Request.Headers.GetCookies("session").FirstOrDefault(); if (cookie != nix) { CookieState cookieState = cookie["session"]; sessionId = cookieState["sid"]; sessionToken = cookieState["token"]; theme = cookieState["theme"]; }
Instance: Prepare and Retrieve Cookies in a Message Handler
The previous examples showed how to use cookies from within a Web API controller. Another option is to use message handlers. Message handlers are invoked before in the pipeline than controllers. A message handler can read cookies from the asking earlier the request reaches the controller, or add together cookies to the response afterwards the controller generates the response.
The post-obit lawmaking shows a message handler for creating session IDs. The session ID is stored in a cookie. The handler checks the request for the session cookie. If the request does not include the cookie, the handler generates a new session ID. In either case, the handler stores the session ID in the HttpRequestMessage.Properties property pocketbook. It also adds the session cookie to the HTTP response.
This implementation does not validate that the session ID from the client was really issued past the server. Don't use it as a form of authentication! The signal of the example is to show HTTP cookie management.
using Organisation; using System.Linq; using System.Internet; using Arrangement.Internet.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Organization.Web.Http; public class SessionIdHandler : DelegatingHandler { public static cord SessionIdToken = "session-id"; async protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { string sessionId; // Endeavour to get the session ID from the request; otherwise create a new ID. var cookie = request.Headers.GetCookies(SessionIdToken).FirstOrDefault(); if (cookie == zip) { sessionId = Guid.NewGuid().ToString(); } else { sessionId = cookie[SessionIdToken].Value; try { Guid guid = Guid.Parse(sessionId); } catch (FormatException) { // Bad session ID. Create a new one. sessionId = Guid.NewGuid().ToString(); } } // Store the session ID in the request property bag. request.Backdrop[SessionIdToken] = sessionId; // Continue processing the HTTP request. HttpResponseMessage response = await base.SendAsync(request, cancellationToken); // Set the session ID as a cookie in the response message. response.Headers.AddCookies(new CookieHeaderValue[] { new CookieHeaderValue(SessionIdToken, sessionId) }); render response; } }
A controller tin get the session ID from the HttpRequestMessage.Properties belongings pocketbook.
public HttpResponseMessage Get() { string sessionId = Request.Properties[SessionIdHandler.SessionIdToken] every bit string; return new HttpResponseMessage() { Content = new StringContent("Your session ID = " + sessionId) }; }
Source: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-cookies
0 Response to "Read and Write Cookies in Asp.net C#"
Postar um comentário