asp.net web api2 通过cookie进行身份验证

asp.net web api传送门:

  1. 跨域请求支持
  2. swagger在线接口文档

浏览器每次发送请求的时候都会带上cookie,我们可以通过这个来进行用户的身份验证

本文将通过特性来判断请求头中是否含有setCookie

设置cookie

HttpCookie cookie = new HttpCookie("UserInfo");//初使化并设置Cookie的名称
cookie.HttpOnly = true;      //设置cookie只有服务器才能访问
cookie.Values["name"] = "小明";       //设置cookie的值
cookie.Values["age"] = 21;
HttpContext.Current.Response.AppendCookie(cookie);     //将cookie添加到响应信息中

将cookie的过期时间设为负数,可以达到清除cookie的效果

HttpCookie cookie = new HttpCookie("UserInfo");
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.AppendCookie(cookie);

更加详细的用法:参考地址

获取cookie

HttpContext context = HttpContext.Current;
HttpCookie cookie = context.Request.Cookies["UserInfo"];
string name = cookie["name"];

使用特性判断请求是否携带cookie

首先,创建特性类:CookieCheckAttribute

public class CookieCheckAttribute : Attribute, IAuthorizationFilter
    {
        public bool AllowMultiple { get; }

        public async Task ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func> continuation)
        {
            IEnumerable headers;
            if (actionContext.Request.Headers.TryGetValues(name: "Cookie", out headers))
            {
            //如果存在Cookie,就继续访问api接口
                return await continuation();
            }
            //如果没有Cookie,就返回错误信息
            return new HttpResponseMessage {
                Content = new StringContent(JsonConvert.SerializeObject(new {
                    result=-1,
                    message="请先登录!"
                }))
            };
        }
    }

使用: 只需要在方法前加上 [CookieCheck] 即可

[CookieCheck]
[HttpPost]
public string GetName(string id)
 {
    return "小明";
 }

你可能感兴趣的:(后端开发)