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

来源:http://www.cnblogs.com/dongqidongqi/archive/2017/02/17/6410079.html
-Advertisement-
Play Games

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 W ...


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中發送和接收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.
本小節給出在HTTP層面上如何實現Cookies,詳細參考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是伺服器在HTTP響應中發送的一個數據片段。客戶端存儲此Cookie(可選),併在後繼的請求中返回它。這讓客戶端和伺服器端可以共用狀態。為了設置一個Cookie,伺服器需要在響應中包含一個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返回給伺服器,客戶端在後繼的請求中要包含一個Cookie報頭。

Cookie: session-id=1234567

An HTTP response can include multiple Set-Cookie headers.
一個HTTP響應可以包含多個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(主域,或簡稱為):告訴客戶端哪一個域應當接收此Cookie。例如,如果Domain是“example.com”,那麼客戶端要把Cookie返回給example.com的每個子域。如果未指定,這個域便是原伺服器。
  • 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(過期):設置Cookie的過期日期。當Cookie過期時,客戶端刪除此Cookie。
  • Max-Age: Sets the maximum age for the cookie. The client deletes the cookie when it reaches the maximum age.
    Max-Age(最大年齡):設置Cookie的最大年齡。當Cookie達到最大年齡時,客戶端刪除此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都設置,則Max-Age優先。如果都未設置,在當前會話結束時,客戶端刪除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的數目。出於私有原因,客戶端通常會拒絕與源伺服器域不匹配的“第三方”Cookie。簡言之,伺服器不應該對取回它所設置的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響應添加Cookie,需要創建一個表示Cookie的CookieHeaderValue實例。然後調用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實例數組。

To extract the cookies from a client request, call the GetCookies method:
為了提取客戶端請求的Cookie,需要調用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
結構化的Cookie數據

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數 — Cookie總數和每個域的Cookie數。因此,把結構化的數據放入一個Cookie而不是設置多個Cookie可能是有用的。

RFC 6265 does not define the structure of cookie data.
RFC 6265並未定義Cookie數據的結構。

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數據傳遞一組“名字-值”對。這些“名字-值”對是在Set-Cookie報頭中作為URL編碼的表單數據進行編碼的:

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:
上述代碼產生以下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
示例:在消息處理器中設置和接收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,也可以稱為消息處理程式 — 譯者註)”。消息處理器的調用在請求管線中要早於控制器。消息處理器可以在請求到達控制器之前讀取請求的Cookie,或者,在控制器生成響應之後將Cookie添加到響應(如下圖所示)。

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.
以下代碼演示了一個創建會話ID的消息處理器。會話ID是存儲在一個Cookie中的。該處理器檢查請求的會話Cookie。如果請求不包含Cookie,處理器便生成一個新會話的ID。在任一情況下,處理器都會將這個會話ID存儲在HttpRequestMessage.Properties屬性包中。它也將這個會話Cookie添加到HTTP響應。

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實際是由伺服器發佈的,該實現不會驗證它。不要把它用於認證場合!本例的關鍵是演示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,否則創建一個新的ID var 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. // 劣質會話ID,創建一個新的 sessionId = Guid.NewGuid().ToString(); } }
// Store the session ID in the request property bag. // 在請求的屬性包中存儲會話ID request.Properties[SessionIdToken] = sessionId;
// Continue processing the HTTP request. // 繼續處理HTTP請求 HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
// Set the session ID as a cookie in the response message. // 將會話ID設置為響應消息中的一個Cookie response.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) }; }

 

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

參考頁面:

http://www.yuanjiaocheng.net/webapi/action-method-returntype.html

http://www.yuanjiaocheng.net/webapi/web-api-reqresq-format.html

http://www.yuanjiaocheng.net/webapi/media-formatter.html

http://www.yuanjiaocheng.net/webapi/webapi-filters.html

http://www.yuanjiaocheng.net/webapi/create-crud-api-1.html

it學習資料


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 簡介 RabbitMQ:一個消息系統,基於 AMQP 系統協議。 優點:健壯、使用簡單、開源和支持各種流行的語言等。 MQ(Message Queue):消息隊列的簡稱,是一種應用程式之間的通信機制。 用途:將無需立即回調獲取返回結果,並且耗時的操作,使用非同步處理的方式提高伺服器的吞吐量及性能。 ...
  • 初步應用vs2012這軟體,語言選擇c# , 框架選擇4(不要選擇最前和太後的框架)然後改個名字和保存路徑點確定就行了。 在main函數中寫代碼,大括弧裡面。 首先是最基本的輸入與輸出: Console.WriteLine(");//直接會輸出引號裡面的內容(如果直接寫入Write的話就不會換行。) ...
  • 電子面單開發流程 服務程式 生成單號,改變三個表: 抓類型表,抓取未處理的充值記錄->根據類型取面單類型表的最大單號(判斷是否在起始和結束之間,並設置郵件或者簡訊預警 )->根據單號規則和充值的數量生成單號明細入單號明細表,改變充值記錄的處理狀態 改變面單類型最大單號(事務提交)。 ...
  • 經過本周的努力,昨晚終於完成OSS.Social微信項目的標準庫支持,當前項目你已經可以同時在.net framework和.net core 中進行調用,調用方法也發生了部分變化,這裡我簡單分享下,主要包含下邊幾個部分: · 移植後的變化 · 和OSS.Common,OSS.Http關係 · 非同步 ...
  • #define aaa //放在代碼最前面 int a = 1; a = a + 1; #if !aaa {a = a + 1;}#elif !aaaaa {a=a+11;}#endif Console.WriteLine(a); Console.ReadKey(); 據說與版本有關 ,#undef ...
  • 為什麼叫T4?因為簡寫為4個T。 T4(Text Template Transformation Toolkit)是微軟官方在VisualStudio 2008中開始使用的代碼生成引擎。在 Visual Studio 中,“T4 文本模板”是由一些文本塊和控制邏輯組成的混合模板,它可以生成文本文件。 ...
  • 在大型網站系統中,為了提高系統訪問性能,往往會把一些不經常變得內容發佈成靜態頁,比如商城的產品詳情頁,新聞詳情頁,這些信息一旦發佈後,變化的頻率不會很高,如果還採用動態輸出的方式進行處理的話,肯定會給伺服器造成很大的資源浪費。但是我們又不能針對這些內容都獨立製作靜態頁,所以我們可以在系統中利用偽靜態 ...
  • Static Using static using聲明允許直接調用靜態方法而不需要指定類名: C# 5 C# 6 Expression-Bodied Methods 使用expression-bodied methods,一個只有一句statement的函數可以使用lambda寫法。 C# 5 C# ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...