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

简介: 原文:【ASP.NET Web API教程】5.5 ASP.NET Web API中的HTTP Cookie5.5 HTTP Cookies in ASP.NET Web API 5.5 ASP.NET Web API中的HTTP Cookie 本文引自:http://www.
原文: 【ASP.NET Web API教程】5.5 ASP.NET Web API中的HTTP Cookie

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) }; }

看完此文如果觉得有所收获,请给个推荐

目录
相关文章
|
20天前
Servlet 教程 之 Servlet 服务器 HTTP 响应 2
Servlet教程讲解了如何通过HttpServletResponse设置HTTP响应,包括编码URL、添加cookie、设置报头、控制缓冲区、发送错误或重定向响应。方法如encodeURL、addCookie、sendError、sendRedirect等,涉及状态码、报头、字符编码和内容长度的管理。
21 2
|
21天前
|
XML Java 数据格式
Servlet 教程 之 Servlet 客户端 HTTP 请求 3
该教程展示了如何在Servlet中处理客户端HTTP请求,特别是获取HTTP头信息。示例代码创建了一个名为`DisplayHeader`的Servlet,它扩展了`HttpServlet`并重写了`doGet`方法。在`doGet`中,使用`HttpServletRequest`的`getHeaderNames()`遍历所有头部,显示其名称和对应值。Servlet在TomcatTest项目下,通过`web.xml`配置映射到`/TomcatTest/DisplayHeader`路径。
31 14
|
1月前
|
API 网络安全 数据安全/隐私保护
.NET邮箱API发送邮件的方法有哪些
本文介绍了.NET开发中使用邮箱API发送邮件的方法,包括SmtpClient类发送邮件、MailMessage类创建邮件消息、设置SmtpClient属性、同步/异步发送、错误处理、发送HTML格式邮件、带附件邮件以及多人邮件。AokSend提供高触达发信服务,适用于大规模验证码发送场景。了解这些技巧有助于开发者实现高效、可靠的邮件功能。
|
21天前
|
安全 Java 网络安全
Servlet 教程 之 Servlet 客户端 HTTP 请求 2
Servlet教程介绍了如何在Servlet中处理HTTP请求,包括获取Cookie、头信息、参数、Session等。方法如:`getCookies()`、`getAttributeNames()`、`getHeaderNames()`、`getParameterNames()`等。还能获取身份验证类型、字符编码、MIME类型、请求方法、远程用户信息、URL路径、安全通道状态以及请求内容长度等。此外,可通过`getSession()`创建或获取Session,并以`Map`形式获取参数。
24 8
|
20天前
|
XML Java 数据格式
Servlet 教程 之 Servlet 服务器 HTTP 响应 3
`Servlet`教程示例展示了如何创建一个HTTP响应,使用`@WebServlet("/Refresh")`的`Refresh`类继承`HttpServlet`。在`doGet`方法中,设置了`Refresh`头以每5秒自动刷新,并用`setContentType("text/html;charset=UTF-8")`设定内容类型。还使用`Calendar`和`SimpleDateFormat`获取并格式化当前时间显示。相应的`web.xml`配置指定了Servlet路径。当访问此Servlet时,页面将每5秒更新一次显示的系统时间。
20 4
|
20天前
|
数据安全/隐私保护
Servlet 教程 之 Servlet HTTP 状态码 1
Servlet教程讲解了HTTP状态码,如200(成功)、404(未找到)和500(服务器错误)。状态码帮助标识HTTP响应的状态,包括继续请求、重定向、权限问题、方法不允许和服务器故障等不同情况。这些代码是通信中的关键反馈元素。
16 3
|
2天前
|
JSON Android开发 数据格式
android与Web服务器交互时的cookie使用-兼谈大众点评数据获得(原创)
android与Web服务器交互时的cookie使用-兼谈大众点评数据获得(原创)
10 2
|
9天前
|
存储 前端开发 搜索推荐
12:会话跟踪技术Cookie的深度应用与实践-Java Web
12:会话跟踪技术Cookie的深度应用与实践-Java Web
22 4
|
14天前
|
存储 缓存 JSON
【Web开发】会话管理与无 Cookie 环境下的实现策略
【Web开发】会话管理与无 Cookie 环境下的实现策略
|
19天前
|
Java
Servlet 教程 之 Servlet HTTP 状态码 3
该Servlet教程聚焦于HTTP状态码,示例展示如何向客户端发送407错误,提示"Need authentication!!!". 类名为`showError`的Servlet扩展自`HttpServlet`,重写`doGet`和`doPost`方法。当遇到GET或POST请求时,它会设置HTTP状态码为407并附带错误信息。
12 2