日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

【ASP.NET Web API教程】5.5 ASP.NET Web API中的HTTP Cookie

發(fā)布時間:2025/3/20 asp.net 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【ASP.NET Web API教程】5.5 ASP.NET Web API中的HTTP Cookie 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

5.5 HTTP Cookies in ASP.NET Web API
5.5 ASP.NET Web API中的HTTP Cookie

本文引自:http://www.asp.net/web-api/overview/working-with-http/http-cookies

By Mike Wasson|September 17, 2012
作者:Mike Wasson | 日期:2012-9-17

This topic describes how to send and receive HTTP cookies in Web API.
本主題描述如何在Web API中發(fā)送和接收HTTP Cookie。

Background on HTTP Cookies
HTTP Cookie的背景知識

This section gives a brief overview of how cookies are implemented at the HTTP level. For details, consult RFC 6265.
本小節(jié)給出在HTTP層面上如何實現(xiàn)Cookies,詳細(xì)參考RFC 6265。

A cookie is a piece of data that a server sends in the HTTP response. The client (optionally) stores the cookie and returns it on subsequet requests. This allows the client and server to share state. To set a cookie, the server includes a Set-Cookie header in the response. The format of a cookie is a name-value pair, with optional attributes. For example:
Cookie是服務(wù)器在HTTP響應(yīng)中發(fā)送的一個數(shù)據(jù)片段。客戶端存儲此Cookie(可選),并在后繼的請求中返回它。這讓客戶端和服務(wù)器端可以共享狀態(tài)。為了設(shè)置一個Cookie,服務(wù)器需要在響應(yīng)中包含一個Set-Cookie報頭。Cookie的格式是一個“名字-值”對,并帶有一些可選屬性。例如:

Set-Cookie: session-id=1234567

Here 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 later requests.
為了將一個Cookie返回給服務(wù)器,客戶端在后繼的請求中要包含一個Cookie報頭。

Cookie: session-id=1234567

An HTTP response can include multiple Set-Cookie headers.
一個HTTP響應(yīng)可以包含多個Set-Cookie報頭。

Set-Cookie: session-token=abcdef; Set-Cookie: session-id=1234567;

The client returns multiple cookies using a single Cookie header.
客戶端用一個單一的Cookie報頭返回多個Cookie。

Cookie: session-id=1234567; session-token=abcdef;

The scope and duration of a cookie are controlled by following attributes in the Set-Cookie header:
Cookie的范圍和期限是受Set-Cookie報頭的以下屬性控制的:

  • 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.
    Domain(主域,或簡稱為):告訴客戶端哪一個域應(yīng)當(dāng)接收此Cookie。例如,如果Domain是“example.com”,那么客戶端要把Cookie返回給example.com的每個子域。如果未指定,這個域便是原服務(wù)器。
  • Path: Restricts the cookie to the specified path within the domain. If not specified, the path of the request URI is used.
    Path(路徑):將Cookie限制到主域的特定路徑。如果未指定,則使用請求URI的路徑。
  • Expires: Sets an expiration date for the cookie. The client deletes the cookie when it expires.
    Expires(過期):設(shè)置Cookie的過期日期。當(dāng)Cookie過期時,客戶端刪除此Cookie。
  • Max-Age: Sets the maximum age for the cookie. The client deletes the cookie when it reaches the maximum age.
    Max-Age(最大年齡):設(shè)置Cookie的最大年齡。當(dāng)Cookie達(dá)到最大年齡時,客戶端刪除此Cookie。

If both Expires and Max-Age are set, Max-Age takes precedence. If neither is set, the client deletes the cookie when the current session ends. (The exact meaning of “session” is determined by the user-agent.)
如果Expires和Max-Age都設(shè)置,則Max-Age優(yōu)先。如果都未設(shè)置,在當(dāng)前會話結(jié)束時,客戶端刪除Cookie。(“會話”的確切含意是由用戶代理確定的。)

However, 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 reject “third party” cookies, where the domain does not match the origin server. In short, the server should not rely on getting back the cookies that it sets.
然而,要意識到客戶端可能會忽略Cookie。例如,一個用戶可能由于私人原因禁用了Cookies??蛻舳丝赡軙谶^期之前刪除Cookies,或限制保存Cookies的數(shù)目。出于私有原因,客戶端通常會拒絕與源服務(wù)器域不匹配的“第三方”Cookie。簡言之,服務(wù)器不應(yīng)該對取回它所設(shè)置的Cookie有依賴性。

Cookies in Web API
Web API中的Cookies

To add a cookie to an HTTP response, create a CookieHeaderValue instance that represents the cookie. Then call the AddCookies extension method, which is defined in the System.Net.Http. HttpResponseHeadersExtensions class, to add the cookie.
為了對一個HTTP響應(yīng)添加Cookie,需要創(chuàng)建一個表示Cookie的CookieHeaderValue實例。然后調(diào)用AddCookies擴展方法(這是在System.Net.Http.HttpResponseHeadersExtensions類中定義的),以添加一個Cookie。

For example, the following code adds a cookie within a controller action:
例如,以下代碼在一個控制器動作中添加了一個Cookie:

public HttpResponseMessage Get() { var resp = new HttpResponseMessage();
var cookie = new CookieHeaderValue("session-id", "12345"); cookie.Expires = DateTimeOffset.Now.AddDays(1); cookie.Domain = Request.RequestUri.Host; cookie.Path = "/";
resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); return resp; }

Notice that AddCookies takes an array of CookieHeaderValue instances.
注意,AddCookies采用的是一個CookieHeaderValue實例數(shù)組。

To extract the cookies from a client request, call the GetCookies method:
為了提取客戶端請求的Cookie,需要調(diào)用GetCookies方法:

string sessionId = "";
CookieHeaderValue cookie = Request.Headers.GetCookies("session-id").FirstOrDefault(); if (cookie != null) { sessionId = cookie["session-id"].Value; }

A CookieHeaderValue contains a collection of CookieState instances. Each CookieState represents one cookie. Use the indexer method to get a CookieState by name, as shown.
CookieHeaderValue含有CookieState實例的集合。每個CookieState表示一個Cookie。使用索引器方法(指上述代碼最后一行的cookie["session-id"] — 譯者注)可以得到由名稱表示的CookieState,如上所示。

Structured Cookie Data
結(jié)構(gòu)化的Cookie數(shù)據(jù)

Many browsers limit how many cookies they will store—both the total number, and the number per domain. Therefore, it can be useful to put structured data into a single cookie, instead of setting multiple cookies.
許多瀏覽器會限制其存儲的Cookie數(shù) — Cookie總數(shù)和每個域的Cookie數(shù)。因此,把結(jié)構(gòu)化的數(shù)據(jù)放入一個Cookie而不是設(shè)置多個Cookie可能是有用的。

RFC 6265 does not define the structure of cookie data.
RFC 6265并未定義Cookie數(shù)據(jù)的結(jié)構(gòu)。

Using the CookieHeaderValue class, you can pass a list of name-value pairs for the cookie data. These name-value pairs are encoded as URL-encoded form data in the Set-Cookie header:
使用CookieHeaderValue類,你可以為Cookie數(shù)據(jù)傳遞一組“名字-值”對。這些“名字-值”對是在Set-Cookie報頭中作為URL編碼的表單數(shù)據(jù)進(jìn)行編碼的:

var resp = new HttpResponseMessage();
var nv = new NameValueCollection(); nv["sid"] = "12345"; nv["token"] = "abcdef"; nv["theme"] = "dark blue"; var cookie = new CookieHeaderValue("session", nv);
resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });

The previous code produces the following Set-Cookie header:
上述代碼產(chǎn)生以下Set-Cookie報頭:

Set-Cookie: session=sid=12345&token=abcdef&theme=dark+blue;

The CookieState class provides an indexer method to read the sub-values from a cookie in the request message:
CookieState類提供了一個索引器方法,以讀取請求消息中Cookie的子值(Sub-values):

string sessionId = ""; string sessionToken = ""; string theme = "";
CookieHeaderValue cookie = Request.Headers.GetCookies("session").FirstOrDefault(); if (cookie != null) { CookieState cookieState = cookie["session"];
sessionId = cookieState["sid"]; sessionToken = cookieState["token"]; theme = cookieState["theme"]; }

Example: Set and Retrieve Cookies in a Message Handler
示例:在消息處理器中設(shè)置和接收Cookie

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 earlier in the pipeline than controllers. A message handler can read cookies from the request before the request reaches the controller, or add cookies to the response after the controller generates the response.
前述示例演示了如何使用來自Web API控制器的Cookie。另一種選擇是使用“消息處理器(Message Handler,也可以稱為消息處理程序 — 譯者注)”。消息處理器的調(diào)用在請求管線中要早于控制器。消息處理器可以在請求到達(dá)控制器之前讀取請求的Cookie,或者,在控制器生成響應(yīng)之后將Cookie添加到響應(yīng)(如下圖所示)。

The following code 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 bag. It also adds the session cookie to the HTTP response.
以下代碼演示了一個創(chuàng)建會話ID的消息處理器。會話ID是存儲在一個Cookie中的。該處理器檢查請求的會話Cookie。如果請求不包含Cookie,處理器便生成一個新會話的ID。在任一情況下,處理器都會將這個會話ID存儲在HttpRequestMessage.Properties屬性包中。它也將這個會話Cookie添加到HTTP響應(yīng)。

This implementation does not validate that the session ID from the client was actually issued by the server. Don't use it as a form of authentication! The point of the example is to show HTTP cookie management.
如果客戶端的會話ID實際是由服務(wù)器發(fā)布的,該實現(xiàn)不會驗證它。不要把它用于認(rèn)證場合!本例的關(guān)鍵是演示HTTP Cookie的管理。

using System; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Web.Http;
public class SessionIdHandler : DelegatingHandler { static public string SessionIdToken = "session-id";
async protected override Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { string sessionId;
// Try to get the session ID from the request; otherwise create a new ID. // 嘗試獲取請求的會話ID,否則創(chuàng)建一個新的IDvar cookie = request.Headers.GetCookies(SessionIdToken).FirstOrDefault(); if (cookie == null) { sessionId = Guid.NewGuid().ToString(); } else { sessionId = cookie[SessionIdToken].Value; try { Guid guid = Guid.Parse(sessionId); } catch (FormatException) { // Bad session ID. Create a new one. // 劣質(zhì)會話ID,創(chuàng)建一個新的sessionId = Guid.NewGuid().ToString(); } }
// Store the session ID in the request property bag. // 在請求的屬性包中存儲會話ID request.Properties[SessionIdToken] = sessionId;
// Continue processing the HTTP request. // 繼續(xù)處理HTTP請求HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
// Set the session ID as a cookie in the response message. // 將會話ID設(shè)置為響應(yīng)消息中的一個Cookieresponse.Headers.AddCookies(new CookieHeaderValue[] { new CookieHeaderValue(SessionIdToken, sessionId) });
return response; } }

A controller can get the session ID from the HttpRequestMessage.Properties property bag.
控制器可以通過HttpRequestMessage.Properties屬性包來獲取會話ID。

public HttpResponseMessage Get() { string sessionId = Request.Properties[SessionIdHandler.SessionIdToken] as string;
return new HttpResponseMessage() { Content = new StringContent("Your session ID = " + sessionId) }; }

看完此文如果覺得有所收獲,請給個推薦

總結(jié)

以上是生活随笔為你收集整理的【ASP.NET Web API教程】5.5 ASP.NET Web API中的HTTP Cookie的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 一区二区三区在线观看免费视频 | 国产精品国产三级国产传播 | 免费在线观看黄视频 | 亚洲人成电影一区二区在线 | 欧美成人69| 男女网站视频 | 亚洲国产综合久久 | 亚洲国产成人精品久久久 | 欧美日韩一区二区视频在线观看 | 中文字幕免费在线播放 | 恶虐女帝安卓汉化版最新版本 | 99在线看| 麻豆一区二区三区四区 | a爱视频| 久久久国| 国产aaa大片| 国产美女主播在线 | 久久久久久伦理 | 少妇天天干 | 亚洲色图二区 | 用力挺进新婚白嫩少妇 | 熟妇女人妻丰满少妇中文字幕 | 久久综合久久网 | 97精品人妻一区二区三区 | 久草久草久草 | 野外做受又硬又粗又大视频√ | 超碰人人网 | 精品人伦一区二区三区 | 91精品国产麻豆国产自产在线 | 两性av| 欧美 日韩 国产 亚洲 色 | 色www情 | 99久久久精品免费观看国产 | 成人1区| 青青草成人免费在线视频 | 99re这里只有精品6 | 亚洲精品乱码久久久久久按摩观 | 久久国产视频网站 | 蜜臀av性久久久久蜜臀aⅴ涩爱 | 欧美一区久久 | 日本xx片 | 青青草久久伊人 | 黄视频在线免费看 | av色资源 | 欧美极品在线观看 | 97色干 | 香蕉久久国产av一区二区 | 国产精品久久久久久久av | 国产亚洲欧美精品久久久久久 | 悠悠色综合 | 校园激情av | av网站大全在线 | 成人福利影院 | 懂色av一区二区三区蜜臀 | 制服师生在线 | 97视频久久| 国产一级片视频 | 国产福利精品在线观看 | 欧洲色综合| 亚洲作爱 | 钰慧的mv视频在线观看 | 欧美大胆a | 国产不卡在线视频 | 美女网站视频在线观看 | 中文字幕在线视频不卡 | 免费在线视频一区 | 日本不卡一二三 | 就要爱爱tv| 奇米av在线 | 男女性杂交内射妇女bbwxz | 天天操天天操天天操天天操天天操 | 激情综合丁香五月 | 68日本xxxxxⅹxxx59 | 中文字幕亚洲专区 | 亚洲午夜精品在线 | 国产一区2| 亚洲区小说区 | 亚洲三级在线观看 | 久热伊人 | 国产www精品| 国产精品白浆一区二小说 | 欧美卡一卡二卡三 | 国产性生活 | 亚洲阿v天堂 | 国产又粗又硬 | 久久久7777 | 久久精品香蕉视频 | 一区二区三区视频在线 | 成人黄色三级 | fc2ppv在线观看 | 美女在线网站 | 波多野结衣在线 | 日韩网站在线播放 | 亚洲福利视频导航 | 在线成人免费电影 | 青青草这里只有精品 | 国产精品v欧美精品v日韩精品 | 1区2区3区在线观看 久久久久久久久久久影院 成人网址在线观看 | 天天射夜夜 |