Cookie的几个参数:

Domain、Path、Expires、Max-Age

如果Expires与Max-Age都存在,Max-Age优先级高,如果都没有设置cookie会在会话结束后删除cookie

WebAPI中使用Cookie

//写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;
} //获取cookie
string sessionId = ""; CookieHeaderValue cookie = Request.Headers.GetCookies("session-id").FirstOrDefault();
if (cookie != null)
{
sessionId = cookie["session-id"].Value;
}

由于浏览器对cookie有一些限制,在单个cookie中存储结构化的数据是一个不错的选择,而不用设置多个cookie。

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

结果:

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

从cookie中读取结构化的数据

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"];
}

在Message Handler中可以对cookie进行处理

一个Demo:

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<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
string sessionId; // Try to get the session ID from the request; otherwise create a new 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.
sessionId = Guid.NewGuid().ToString();
}
} // Store the session ID in the request property bag.
request.Properties[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)
}); return response;
}
} public HttpResponseMessage Get()
{
string sessionId = Request.Properties[SessionIdHandler.SessionIdToken] as string; return new HttpResponseMessage()
{
Content = new StringContent("Your session ID = " + sessionId)
};
}

WebApi2官网学习记录---Cookie的更多相关文章

  1. WebApi2官网学习记录---批量处理HTTP Message

    原文:Batching Handler for ASP.NET Web API 自定义实现HttpMessageHandler public class BatchHandler : HttpMess ...

  2. WebApi2官网学习记录---Html Form Data

    HTML Forms概述 <form action="api/values" method="post"> 默认的method是GET,如果使用GE ...

  3. WebApi2官网学习记录--HttpClient Message Handlers

    在客户端,HttpClient使用message handle处理request.默认的handler是HttpClientHandler,用来发送请求和获取response从服务端.可以在clien ...

  4. WebApi2官网学习记录--HTTP Message Handlers

    Message Handlers是一个接收HTTP Request返回HTTP Response的类,继承自HttpMessageHandler 通常,一些列的message handler被链接到一 ...

  5. WebApi2官网学习记录---Configuring

    Configuration Settings WebAPI中的configuration settings定义在HttpConfiguration中.有一下成员: DependencyResolver ...

  6. WebApi2官网学习记录--- Authentication与Authorization

    Authentication(认证)   WebAPI中的认证既可以使用HttpModel也可以使用HTTP message handler,具体使用哪个可以参考一下依据: 一个HttpModel可以 ...

  7. WebApi2官网学习记录---单元测试

    如果没有对应的web api模板,首先使用nuget进行安装 例子1: ProductController 是以硬编码的方式使用StoreAppContext类的实例,可以使用依赖注入模式,在外部指定 ...

  8. WebApi2官网学习记录---Tracing

    安装追踪用的包 Install-Package Microsoft.AspNet.WebApi.Tracing Update-Package Microsoft.AspNet.WebApi.WebHo ...

  9. WebApi2官网学习记录---异常处理

    HttpResponseException 当WebAPI的控制器抛出一个未捕获的异常时,默认情况下,大多数异常被转为status code为500的http response即服务端错误. Http ...

随机推荐

  1. 【转】tkinter实现的文本编辑器

    此代码是看完如下教学视频实现的,所以算是[转载]吧: 效果:                                                     代码: # -*- encodin ...

  2. spring项目中监听器作用-ContextLoaderListener(项目启动时,加载一些东西到缓存中)

    作用:在启动Web容器时,自动装配Spring applicationContext.xml的配置信息. 因为它实现了ServletContextListener这个接口,在web.xml配置这个监听 ...

  3. ADO.NET之使用DataGridView控件显示从服务器上获取的数据

    今天回顾下ADO.NET中关于使用DataGridiew控件显示数据的相关知识 理论整理: 使用 DataGridView 控件,可以显示和编辑来自多种不同类型的数据源的表格数据. SqlDataAd ...

  4. C#--接口的实现

    接口: 不允许使用访问修饰符,所有接口成员都是公共的. 接口成员不能包含代码体. 接口不能定义字段成员. 接口成员不能使用关键字static,vritual,abstract,sealed来定义. 类 ...

  5. .net转php laraval框架学习系列(二)项目实战---Models

    上一篇已经介绍开发环境的搭建,如果有问题可以在文章后留言. 这篇将从项目实战开发,一步一步了解laravel框架. 在开发mvc项目时,models都是第一步. 下面就从建模开始. 实体关系图 由于不 ...

  6. centos上安装rabbitmq并且python测试

    把我的阿里云重置了一下,重新安装rabbitmq,看看会出现什么问题. 首先,把erlang环境安装一下,直接 yum list | grep erlang erlang.x86_64 R16B-03 ...

  7. Java学习笔记--PriorityQueue(优先队列)(堆)

    PriorityQueue(优先队列)实际上是一个堆(不指定Comparator时默认为最小堆)队列既可以根据元素的自然顺序来排序,也可以根据 Comparator来设置排序规则.队列的头是按指定排序 ...

  8. iOS开发 自定义navigationleftItem 之后手势失效的问题

    @property (nonatomic, strong) UIViewController *currentShowVC; //设置代理 self.navigationController.inte ...

  9. 关于开源中文搜索引擎架构coreseek中算法详解

     Coreseek 是一款中文全文检索/搜索软件,以GPLv2许可协议开源发布,基于Sphinx研发并独立发布,专攻中文搜索和信息处理领域,适用于行业/垂直搜索.论坛/站内搜索.数据库搜索.文档/文献 ...

  10. Codeforces 161D Distance in Tree

    题目大意:给出一棵n个节点的树,统计树中长度为k的路径的条数(1<=n<=50000 , 1<=k<=500) 思路:树分治! #include<cstdio> # ...